How do I concatenate two lists in Python?
Just add them together using the + operator:
It's as simple as that. This method maintains the order and contents and leaves the originals untouched. Great for those "get-in, get-out" moments in coding.
Multi-solution sprint
Now let's dive into some of the other concatenation methods and discuss their use-cases:
Unpacking operator
The * unpacking operator, an avantgarde choice since Python 3.5:
Extend for the win
Want to grow your list without making more? Use the extend() method:
This modifies list_one without the need for a new list.
itertools.chain - smart and efficient
When dealing with large or multiple lists, trust itertools.chain() to handle it smoothly:
Or, for lists containing lists:
No intermediate lists ensure we're being memory efficient.
heapq.merge: a sorted affair
When your sorted lists need friendly merging, heapq.merge is the perfect cup of tea:
This keeps your combined array sorted.
Manual for loop
If you'd like more control over concatenation:
Size matters: handling large lists
When dealing with big lists, the + operator can hog memory. Here, itertools.chain() proves to be a memory-efficient hero.
Pitfall prevention
To be an effective Pythonista, it's essential to understand common pitfalls and avoid them. Let's discuss some:
Not all sums are equal
Be wary of the sum() function, it often leads to high-runtime complexity:
For functional folks
For fans of the functional paradigm, operator.add is the equivalent of the + operator:
Wacky concatenation: list comprehensions
For a creative approach, enter list comprehensions:
Need originals? Meet their clones
If you need to concatenate but keep originals, hello new variable:
Was this article helpful?