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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With