Reputation: 122142
How to check whether an iterable is the same size after expanding the iterations using zip? E.g.
>>> x = iter([1,2,3])
>>> y = iter([5,6,7,8])
>>> for i,j in zip(x,y):
... print i,j
...
1 5
2 6
3 7
Doing next(x)
after using up the iterable throws an error but i can't try-except it since it's not an Error
:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Is there any way to do the check in a single pass?
Upvotes: 2
Views: 63
Reputation: 19362
Depending on what you are trying to achieve, if you are interested in all values from the itreables, you might consider using itertools.izip_longest
rather than zip
:
>>> import itertools
>>> x = iter([1,2,3])
>>> y = iter([5,6,7,8])
>>> for i, j in itertools.izip_longest(x, y, fillvalue=None):
... print i, j
...
1 5
2 6
3 7
None 8
Upvotes: 1
Reputation: 180461
next
also takes a default value so you can simply use that:
if next(x, None):
# x is not empty
Just make sure to use a default that won't be appearing in your iterable.
It is also possible to use __length_hint__
:
In [4]: x = iter([1, 2, 3])
In [5]: y = iter([5, 6, 7, 8])
In [6]: for i, j in zip(x, y):
...: print(i, j)
...:
(1, 5)
(2, 6)
(3, 7)
In [7]: x.__length_hint__()
Out[7]: 0
In [8]: y.__length_hint__()
Out[8]: 1
Upvotes: 3
Reputation: 116
What do you mean you can't try-except?
try:
x.next()
except StopIteration:
pass
Upvotes: 3