In python, how do I concatenate 3 lists using a list comprehension?
Have:
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]
Want:
allList = [1,2,3,4,5,6,7,8,9,10,11,12]
I tried using a list comprehension, but I'm not very good at them yet. These are what I have tried:
allList = [n for n in list1 for n in list2 for n in list3 ]
this was a bad idea, obviously and yielded len(list1)*len(list2)*len(list3) worth of values. Oops. So I tried this:
allList = [n for n in list1, list2, list3]
but that gave me allList = [list1, list 2, list3] (3 lists of lists)
I know you can concatenate using the + operator (as in x = list1 + list2 + list3)but how do you do this using a simple list comprehension?
There is a similar question here: Concatenate 3 lists of words , but that's for C#.
A better solution is to use itertools.chain
instead of addition. That way, instead of creating the intermediate list list1 + list2
, and then another intermediate list list1 + list2 + list3
, you just create the final list with no intermediates:
allList = [x for x in itertools.chain(list1, list2, list3)]
However, an empty list comprehension like this is pretty silly; just use the list
function to turn any arbitrary iterable into a list:
allList = list(itertools.chain(list1, list2, list3))
Or, even better… if the only reason you need this is to loop over it, just leave it as an iterator:
for thing in itertools.chain(list1, list2, list3):
do_stuff(thing)
While we're at it, the "similar question" you linked to is actually a very different, and more complicated, question. But, because itertools
is so cool, it's still a one-liner in Python:
itertools.product(list1, list2, list3)
Or, if you want to print it out in the format specified by that question:
print('\n'.join(map(' '.join, itertools.product(list1, list2, list3))))
Here are some options:
>>> sum([list1, list2, list3], [])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> list1 + list2 + list3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
With comprehension: (it's really not necessary)
>>> [x for x in sum([list1, list2, list3], [])]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With