1

If we need to swap variables a and b in C or Java, we need to have something (pseudo code) like:

tmp = a;
a = b;
b = tmp;

Why Python can do it by a, b = b, a. What happened with it?

Not sure whether it is the right place for this question. But I do appreciate it if someone could give me some clues.

Ya Xiao
  • 861
  • 8
  • 16
  • 1
    java doesn't support `tuples` – Garr Godfrey Jun 18 '21 at 02:12
  • 3
    Languages can do whatever they're defined to do. Python supports tuples and destructuring assignments, so it can do it. Some other languages support it as well, while some others do not. There's no mystery. Why do some boxes of crayons contain the color gold while others do not? Same reason. – Tom Karzes Jun 18 '21 at 02:12
  • 1
    Not sure what you want to know. Python can do this because sequence packing is part of the language. You can read a bit more in the docs at the [bottom of this section](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences) – Mark Jun 18 '21 at 02:12
  • As far as I know, `a, b = b, a` is just Python shorthand. – Party-with-Programming Jun 18 '21 at 02:14

1 Answers1

4

It's because python provides a special "tuple unpacking" syntax that many other languages don't have. I'll break apart what's going on:

The b, a on the right of the equals is making a tuple (remember, a tuple is pretty much the same as a list, except you can't modify it). The a, b on the left is a different syntax that's unpacking the tuple, i.e. it takes the first item in the tuple, and store it in the first variable listed, then it takes the second item and stored it in the second variable, and so forth.

This is what it looks like broken up in multiple steps:

a = 2
b = 3
my_tuple = a, b
print(my_tuple) # (2, 3)
b, a = my_tuple
print(a) # 3
print(b) # 2

And here's another, simpler examples of tuple unpacking, just to help wrap your mind around it:

x, y, z = (1, 2, 3)
print(x) # 1
print(y) # 2
print(z) # 3

By the way, Python's not the only one, Javascript can do it too, but with arrays:

[a, b] = [b, a];
Scotty Jamison
  • 10,498
  • 2
  • 24
  • 30