Default tuple values

In python you can assign values to a number of variables using tuple unpacking:

foo, bar, baz = some_3_values_tuple

But if the tuple does not have an exact number of values the assignment will fail with ValueError:

>>> some_tuple = 1,2
>>> foo, bar, baz = some_tuple
Traceback (most recent call last):
File "", line 1, in
ValueError: need more than 2 values to unpack

In that case fill up missing values with None:

>>> foo, bar, baz = some_tuple + (None,) * (3 - len(some_tuple))

PS: I like one-liners that can supplement otherwise needed if-elif-else logic 🙂

Leave a Reply

Back to Top