I have a list of tuples, each of which contains between 1 to 5 elements. I'd like to unpack these tuples into five values but that won't work for tuples of less than five elements:
>>> t = (1,2) # or (1) or (1,2,3) or ...
>>> a,b,c,d,e = (t)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
It's ok to set non-existing values to None
. Basically, I'm looking for a better (denser) way if this function:
def unpack(t):
if len(t) == 1:
return t[0], None, None, None, None
if len(t) == 2:
return t[0], t[1], None, None, None
if len(t) == 3:
return t[0], t[1], t[2], None, None
if len(t) == 4:
return t[0], t[1], t[2], t[3], None
if len(t) == 5:
return t[0], t[1], t[2], t[3], t[4]
return None, None, None, None, None
(This questions is somewhat the opposite of this one or this one.)
You can add the remaining elements with:
a, b, c, d, e = t + (None,) * (5 - len(t))
Demo:
>>> t = (1, 2)
>>> a, b, c, d, e = t + (None,) * (5 - len(t))
>>> a, b, c, d, e
(1, 2, None, None, None)
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