Default value in Python unpacking

You could try * unpacking with some post-processing:

a, b, *c = read_json(request)
c = c[0] if c else 2

This will assign a and b as normal. If c is assigned something, it will be a list with one element. If only two values were unpacked, it will be an empty list. The second statement assigns to c its first element if there is one, or the default value of 2 otherwise.

>>> a, b, *c = 1, 2, 3
>>> c = c[0] if c else 2
>>> a
1
>>> b
2
>>> c
3
>>> a, b, *c = 1, 2
>>> c = c[0] if c else 2
>>> a
1
>>> b
2
>>> c
2

Leave a Comment