Question

How can I avoid using nested tuple unpacking when enumerating a list of tuples like this?

for i, (x, y) in enumerate(zip("1234", "ABCD")):
    # do stuff
Was it helpful?

Solution

Use itertools.count to avoid nested tuple unpacking:

from itertools import count

for i, x, y in zip(count(), "1234", "ABCD"):
    # do stuff

OTHER TIPS

That code is fine, and is the cleanest idiom.

Trying to avoid it is solving a non-problem, it's actually worse to use itertools.count than enumerate, because one pitfall is it breaks if we ever use zip_longest/ iterator lengths differ, since count() is an infinite iterator:

itertools.count works if we use zip(), i.e. both iterators are the same length, or we're ok with truncating the longer one to the length of the shorter one:

for i, x, y in itertools.zip_longest(count(), "1234", "ABCD"): print(f'{i}: {x} {y}')

itertools.count breaks (i.e. runs infinitely) if we use izip_longest(), iterators are different length:

for i, x, y in itertools.zip_longest(count(), "1234", "ABCDE"):
    print(f'{i}: {x} {y}')

0: 1 A
1: 2 B
2: 3 C
3: 4 D
4: None E
5: None None
6: None None
...

Since it would be very confusing to have one idiom for iterators of the same size, and another for different-length, we should not generally use count() for that. Even if you know your code won't, somebody may copy.modify your code and hit this. So it's bad idiom.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top