How to Append Another List to a Existing List in Python? (Differ

  • Time:2020-09-09 14:04:20
  • Class:Weblog
  • Read:30

Let’s you have a list in Python:

1
a = [1, 2, 3, 4]
a = [1, 2, 3, 4]

And you have another list in Python:

1
b = [5, 6, 7, 8]
b = [5, 6, 7, 8]

You can concatenate two lists by simply using + operator, which will leave both lists untouched and return a copy of the concatenated list.

1
a + b  # [1, 2, 3, 4, 5, 6, 7, 8]
a + b  # [1, 2, 3, 4, 5, 6, 7, 8]

You can use extend() method of the array, which allows us to append all the elements from another list to it. This will modify the original list.

1
2
3
# c is None
c = a.extend(b)
# a is now [1, 2, 3, 4, 5, 6, 7, 8]
# c is None
c = a.extend(b)
# a is now [1, 2, 3, 4, 5, 6, 7, 8]

The append() on the other hand, appends an element to the list. For example,

1
2
3
a = [1, 2, 3, 4]
a.append(5)
# a is now [1, 2, 3, 4, 5]
a = [1, 2, 3, 4]
a.append(5)
# a is now [1, 2, 3, 4, 5]

The append returns None. You can use append to achieve what the extend does.

1
2
3
def extend(a, b):
  for x in b:
    a.append(x)
def extend(a, b):
  for x in b:
    a.append(x)

–EOF (The Ultimate Computing & Technology Blog) —

Recommend:
How to Improve Your Blog’s Bounce Rate (and Why You Should)
Does Your SME Have A Disaster Recovery Plan?
7 Best SEO Trends Gaining Popularity In 2019
How To Choose The Best Hosting Service For A WordPress Website
An Idiot’s Guide to Email Automation for Bloggers
Checklist for Choosing a Perfect WordPress Blog Theme
15 Mindset Hacks to Avoid Blogging Failure
Can Retailers Refuse Refunds Using POS Software?
How to Create Sponsorship Proposals For Your Blog
7 Top Investment Blogs For Newbie And Veteran Investors
Share:Facebook Twitter
Comment list
Comment add