Concatenating two lists in Python
Lists in Python can be concatenated in two ways
- Using
+
operator - Using
extend
Let list_a
and list_b
be defined as below
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
Using +
operator to concatenate two list_a
and list_b
list_c = list_a + lis_b
print list_c # Output: [1, 2, 3, 4, 5, 6, 7, 8]
If we do not want a new list i.e. list_c
list_a = list_a + list_b
print list_a # Output: [1, 2, 3, 4, 5, 6, 7, 8]
Using extend
extend
operator can be used to concatenate one list into another. It is not possible to store the value into the third list. One of the existing list
has to store the concatenated result.
Want to read this story later? Save it in Journal.
list_c = list_a.extend(list_b)print list_c # Output: NoneTypeprint list_a # Output: [1, 2, 3, 4, 5, 6, 7, 8]print list_b # Output: [5, 6, 7, 8]
In the above example, extends
concatenates the list_b
into list_a
Which is better?
We can use either of the ways to concatenate the list. There is not much difference in performance. +
operators seems to be slightly better. But this difference will be visible only when the concatenation is done a very large number of times
If you like my articles and find them useful, feel free to buy me a coffee. Thanks!
To get updates for my new stories, follow me on medium and twitter
Other articles:
- Beginner’s Guide to ReactJS
- The Journey of JavaScript: from Downloading Scripts to Execution
- Why Progressive Web Apps are great and how to build one
- Let’s get this ‘this’ once and for all
- Service Workers
- Service Workers implementation
- Execution Context in JavaScript
- Virtual DOM in ReactJS
- Prototypes in JavaScript
- ‘this’ in JavaScript
- Object.create in JavaScript
- Inheritance in JavaScript
- Create objects in JavaScript
- Objects in JavaScript
- Zip in Python
- decorators in Python
- Concatenating two lists in Python
- lambda, map, and filter in Python
- List comprehensions in Python
📝 Read this story later in Journal.
👩💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.