Curious tuple-unpacking

110 views Asked by At

I stumbled around a curious behaviour for tuple unpacking, which i could not explain at first. Now while typing this as a SO question it became clear, but i felt it was of enough general interest to post it nevertheless.

def test(rng):
    a, b, c = rng if len(rng) == 3 else rng[0], rng[1], 1
    return a, b, c

>>> test((1, 2, 3))
((1,2,3), 2, 3)     
# expected: (1, 2, 3)

>>> test((1,2))
(1,2,1)

Why does it behave so unexpected at first, but makes sense at second glance?

1

There are 1 answers

1
fredtantini On BEST ANSWER

Just add some parentheses:

>>> def test(rng):
...     a, b, c = rng if len(rng) == 3 else (rng[0], rng[1], 1)
...     return a, b, c
...
>>> test((1, 2, 3))
(1, 2, 3)
>>> test((1,2))
(1, 2, 1)

Currently your line is like:

a, b, c = (rng if len(rng) == 3 else rng[0]), rng[1], 1