Is there any smart way to write a list comprehension over more than one list?
I know I could use a separate range list as index but this way I have to know the length (or get it separately with a len()
function call).
>>> a = range(10)
>>> b = range(10, 0, -1)
>>> [(a[x],b[x]) for x in range(10)]
[(0, 10), (1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)]
I'd love to have something like this:
>>> [(a,b) for a in range(10) and b in range(10, 0, -1)]
[(0, 10), (1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)]
How would you write the list comprehension? Is there a way to do this with itertools?
The range list just stand for any list and I do not necessarily want to get a tuple. there could also be a function which takes a and b as parameters. So zip is not what I want.
UPDATE: With "So zip is not what I want." I meant that I don't want zip(range(10), range(10, 0, -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.
Even factoring out the time it takes to lookup and load the append function, the list comprehension is still faster because the list is created in C, rather than built up one item at a time in Python.
Your example is just:
zip(range(10), range(10, 0, -1))
More generally, you can join any set of iterables using zip
:
[func(a, d, ...) for a, b, ..., n in zip(iterable1, iterable2, ..., iterableN)]
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