How do I concatenate two lists in Python?
Example:
listone = [1,2,3]
listtwo = [4,5,6]
Expected outcome:
joinedlist == [1, 2, 3, 4, 5, 6]
641
77
| |
1171
|
Python makes this ridiculously easy.
| ||||||||||||||||||||
|
104
|
It's also possible to create a generator that simply iterates over the items in both lists. This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:
| ||||||||||||
|
85
|
You can use sets to obtain merged list of unique values
| ||||||||||||||||||||
|
31
|
This is quite simple, I think it was even shown in the tutorial:
| ||
26
|
You could also do
| ||||
|
18
|
You could simply use the
Or:
Also, if you want the values in the merged list to be unique you can do:
| |||
11
|
It's worth noting that the
If an iterable (tuple, list, generator, etc.) is the input, the
| ||
9
|
With Python 3.3+ you can use yield from:
Or, if you want to support an arbitrary number of iterators:
| ||
7
|
If you want to merge the two lists in sorted form, you can use merge function from the heapq library.
| |||
4
|
If you need to merge two ordered lists with complicated sorting rules, you might have to roll it yourself like in the following code (using a simple sorting rule for readability :-) ).
| |||
3
|
As a more general way for more lists you can put them within a list and use
1. Note that | ||
3
|
If you don't want to or can't use the plus operator (
| |||
2
|
You could use the append() method
| ||||
|
1
|
Yes, its that simple. | ||
1
|
Joining two lists in Python:
If you don't want any duplication :
| ||
1
|
This question directly asks about joining two lists. However it's pretty high in search even when you are looking for a way of joining many lists (including the case when you joining zero lists). Consider this more generic approach:
Will output:
Note, this also works correctly when Update Consider better alternative suggested by Patrick Collins in the comments:
| ||||
|
[3,2,1]
? Will the output change? – barkmadley Nov 12 '09 at 7:06