Member-only story

Can You Answer This Without Cheating?

# WHAT IS A & B??

Liu Zuo Lin
3 min readMar 12, 2024

Tuple Unpacking For Those New To This

a = 4
b = 5

^ we can achieve the same thing using tuple unpacking

a, b = 4, 5

Some rules

Rule 1 — the number of variables on the left must be equal to the number of values on the right

a, b = 4, 5, 6    # error
a, b, c = 4, 5 # error

Rule 2 — we can ignore rule 1 if we have one starred expression on the left

a, b, *others = [4, 5, 6, 7, 8, 9]

print(a, b) # 4, 5
print(others) # [6, 7, 8, 9]

Note — there must still be enough variables on the left

a, b, *others = [4]        # error

Switching variables

a = 5
b = 6

a, b = b, a

print(a, b) # 6 5

^ here, we can use tuple unpacking to switch 2 variables’ values.

a = 5
b = 6
c = 7

a, b, c = b, c, a

print(a, b, c) # 6 7 5

^ we can do so with 3+ variables too as long as all rules are followed

a, b = b, a — what this is NOT

--

--

Liu Zuo Lin
Liu Zuo Lin

Written by Liu Zuo Lin

SWE @ Meta | [Ebook] 101 Things I Never Knew About Python: https://payhip.com/b/vywcf

Responses (4)