Joe - 5 months ago 8x

Python Question

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`

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.

Source (Stackoverflow)

Comments