Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack a tuple into more values than the tuple has?

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

like image 981
Jens Avatar asked Mar 06 '15 19:03

Jens


1 Answers

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)
like image 137
Martijn Pieters Avatar answered Sep 25 '22 21:09

Martijn Pieters