Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a nested name as the __getitem__ index of the previous iterable in list comprehensions?

I want to use two for-loops inside a list-comprehension, but I want to use the name of the second as an index of the first iterable. How can I do that?

Example:

l = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
[x for x in l[i] for i in range(len(l))]

Error:

Traceback (most recent call last):
  File "python", line 2, in <module>
NameError: name 'i' is not defined
like image 484
Ericson Willians Avatar asked Aug 11 '15 07:08

Ericson Willians


1 Answers

You have the order of your for loops mixed up. They should be listed in nesting order, the same order you'd use if you wrote out the loops normally:

[x for i in range(len(l)) for x in l[i]]

When in doubt, write out the loops like you'd write them when using statements. Your list comprehension tried to do this:

for x in l[i]:
    for i in range(len(l)):
        x

which makes it more obvious that you tried to access i before you defined it.

like image 82
Martijn Pieters Avatar answered Oct 12 '22 18:10

Martijn Pieters