0

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Don Question
  • 11,227
  • 5
  • 36
  • 54

1 Answers1

3

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
fredtantini
  • 15,966
  • 8
  • 49
  • 55