Ask coding questions

← Back to all posts
How to join two lists with list comprehension in python
Dunce (65)

So this code:

myList = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
newList = [item for item in list]

is equivalent to:

myList = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
newList = []

for item in myList:
  newList.append(item)

But I would like it to be equivalent to:

myList = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
newList = []

for item in myList:
  newList += item

How would I do that?

Answered by IMayBeMe (456) [earned 5 cycles]
View Answer
Comments
hotnewtop
IMayBeMe (456)

This is kind of cheap but it works:

import itertools
myList = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
newList = list(itertools.chain.from_iterable(myList))

Slightly less cheap way:

myList = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
newList = [i for j in myList for i in j]
VulcanWM (2760)

Wait what are you trying to do?

Dunce (65)

@VulcanWM append() adds a single item, but += joins 2 lists. So I want to iterate through a list and join each of its items with another list, using list comprehension.

VulcanWM (2760)

so what output are you trying to get? @Dunce

Dunce (65)

@VulcanWM input:

myList = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Output:

newList = [1, 2, 3, 1, 2, 3, 1, 2, 3]