ellaRT
ellaRT

Reputation: 1366

Nested List comprehension in Python

I have a List inside of a List in Python and i want to convert them into a single list using List comprehension:

>>> aa = [[1,2],[1,2]]
>>> bb = [num for num in numbers for numbers in aa]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'numbers' is not defined
>>>

What am i doing wrong?

*The answer to my question isn't on the duplicate as stated above, it is below this question.

Upvotes: 9

Views: 1895

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90879

You have the for loops in your list comprehension in the opposite order -

bb = [num for numbers in aa for num in numbers]

Demo -

>>> aa = [[1,2],[1,2]]
>>> bb = [num for numbers in aa for num in numbers]
>>> bb
[1, 2, 1, 2]

Upvotes: 9

Related Questions