9

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.

7
  • 7
    for numbers in aa part should come first. Commented Oct 13, 2015 at 6:17
  • 1
    Haha. woah! that was quick. Thank you! @AshwiniChaudhary Commented Oct 13, 2015 at 6:18
  • Possible duplicate of Nested For Loops Using List Comprehension Commented Oct 13, 2015 at 6:57
  • One more link Commented Oct 13, 2015 at 6:58
  • ya same question, but did u see the same answer on those questions that solved my problem? @khajvah Commented Oct 13, 2015 at 7:00

1 Answer 1

9

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]
Sign up to request clarification or add additional context in comments.

2 Comments

yes, yes. Thank you. that was confusing. I thought that i had it in the correct order. :)
python list comprehensions are confusing. unfortunately there is no decent alternative in the language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.