I want to do something like:
all = [ x for x in t[1] for t in tests ]
tests looks like:
[ ("foo",[a,b,c]), ("bar",[d,e,f]) ]
So I want to have the result
all = [a,b,c,d,e,f]
My code does not work, Python says:
UnboundLocalError: local variable 't' referenced before assignment
Is there any simple way to do that?
List comprehensions provide us with a simple way to create a list based on some sequence or another list that we can loop over. In python terminology, anything that we can loop over is called iterable. At its most basic level, list comprehension is a syntactic construct for creating lists from existing lists.
To increment a variable in Python use the syntax += 1 , for example to increment the variable i by 1 write i += 1 .
As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.
It should work the other way around:
all = [x for t in tests for x in t[1]]
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