Joe Joe - 7 months ago 14
Python Question

How this naming variables works?

I am a beginner in python and I found a strange way of naming variables and couldn't understand at all.

Can someone help me please

x = 1
n = [1, 1, 3]
for i in n:
y, x = x, i


i want to understand this line
y, x = x, i
what does it mean?

Answer

It's called tuple unpacking. The right-hand side is just a tuple; the parentheses in an expression like (x, i) are optional when there is no ambiguity. The left-hand side is a sequence of names that are associated with the corresponding value on the right-hand side. The statement is equivalent to

tmp = x, i
y = tmp[0]
x = tmp[1]

The right-hand side is fully evaluated as a tuple before the assignments are made, meaning you can write code like

a, b = b, a

to swap values without needing a temporary variable.

Comments