unpack tuple of wrong size

Robert Brewer fumanchu at amor.org
Tue Apr 6 14:04:21 EDT 2004


Tung Wai Yip wrote:
> t = (1,)
> a,b=t
> 
> I got a "ValueError: unpack tuple of wrong size"
> 
> What I want is for a=1 and b=None. Is there a good way to do this?

The best way is:

t = (1, None)
a, b = t

...but if you *really, really* want implicit instead of explicit:

t = (1, )
try:
    a = t[0]
except ValueError:
    a, b = None, None
else:
    try:
        b = t[1]
    except ValueError:
        b = None

...I tend to prefer the former. ;)

You could also do "the same thing" without the try: blocks:

if t:
    a = t[0]
    if len(t) > 1:
        b = t[1]
    else:
        b = None
else:
    a, b = None, None

...or convert the tuple to a dict and use "get", which defaults to
returning None:

newt = dict(enumerate(t))
a = t.get(0)
b = t.get(1)

...or write a custom subclass of tuple. The options are numerous.


FuManChu




More information about the Python-list mailing list