Skip to content Skip to sidebar Skip to footer

Python List Comprehension: Flattening A List Of Lists Returns A List Of 5s

I have the following list of lists: >>>> vec=[[1,2,3],[4,5,6],[7,8,9]] To flatten a list of lists using list comprehension I can use: >>>>[i for k in vec

Solution 1:

If you're using Python 3 as this question is tagged, then you must have rebound i to 5 at some point. In Python 3 listcomps have their own scope, and so the commands you've shown won't even work:

>>> vec=[[1,2,3],[4,5,6],[7,8,9]]
>>> [i for k in vec for i in k]
[1, 2, 3, 4, 5, 6, 7, 8, 9] 
>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
>>> [i for k in vec]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
NameError: name 'i' is not defined

Because the listcomp doesn't set i to anything, it's trying to get a value from the outer scope, and (unlike you :-) I haven't set it to anything.

By way of contrast, in Python 2, i would leak from the [i for k in vec for i in k] listcomp and you'd wind up with

>>> [i for k in vec]
[9, 9, 9]
>>> [i for k in vec for k in k]
[9, 9, 9, 9, 9, 9, 9, 9, 9]

Post a Comment for "Python List Comprehension: Flattening A List Of Lists Returns A List Of 5s"