Unpack value(s) into variable(s) or None (ValueError: not enough values to unpack)
You can unpack a sequence to three variable using:
one, two, *three = [1,2]
At this point, three
will be an empty list. You can then assign three
to None
using an or
check if three is empty.
three = three or None
Use the *
operator and fill an intermediate iterable with that which you're unpacking and fill the remainder with your default value of choice.
x = [1, 2]
default_value= None
one, two, three = [*x, *([default_value] * (3 - len(x)))]
And a bonus function to handle both cases:
def unpack(source, target, default_value=None):
n = len(source)
if n < target:
return [*source, *([default_value] * (target - len(source)))]
elif n > target:
return source[0:target]
else:
return source
Amend to handle non-iterable input as needed.