Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 513
ellaRT Avatar asked Oct 13 '15 06:10

ellaRT


1 Answers

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]
like image 127
Anand S Kumar Avatar answered Oct 25 '22 07:10

Anand S Kumar