I want to loop through an iterable of tuples and store each value in a new variable. I can do this with zip:
x, y = zip(*enumerate(range(0,30,5)))
But this doesn't work if the iterable is empty
x, y = zip(*enumerate(range(0,-1,5)))
Traceback (most recent call last):
File "C:\Python36\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-35-76960294a673>", line 1, in <module>
x, y = zip(*enumerate(range(0,-1,5)))
ValueError: not enough values to unpack (expected 2, got 0)
Because zip returns an empty iterable instead of an iterable containing two empty lists
How can I handle the case where the iterable is empty?
Awkward special casing:
x, y = [*zip(*your_iterable)] or [(), ()]
or just not using zip(*...)
. Your zip(*enumerate(...))
can be replaced by constructing the indices with range
:
y = tuple(range(0,-1,5))
x = tuple(range(len(y)))
I'm calling tuple
here to replicate the behavior of zip
, but depending on what you're doing, that may not be necessary.