Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python values of multiple lists in one list comprehension

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))

like image 296
dominik Avatar asked Mar 22 '12 16:03

dominik


People also ask

Can you do nested list comprehension?

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.

Are list comprehensions faster than append?

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.


1 Answers

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)]
like image 73
agf Avatar answered Sep 20 '22 17:09

agf