How can I use the sub-name as the __getitem__ index of the previous iterable in the lists?

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

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 
+5
source share
1 answer

You have the mixing order of the for loops. They should be listed in nesting order, the same order you would use if you usually wrote out loops:

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

If in doubt, write the loops as you would write them 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.

+5
source

All Articles