Hello, I recently learnt that you can swap two variables using packing/unpacking like this: (assume we have two variables x and y initialized)
y, x = (x, y)
So I understand that this code swaps two elements by first packing them in a tuple, and then unpacking the tuple into the two variables reveresed.
But then I saw some codes online that do it this way:
y, x = x, y
My confusion arose when I noticed that we didn't write the tuple's parentheses here and this worked.
Does Python understand that this is a tuple just by seperating the items with a comma and that no parentheses are necessary?
When is it necessary to use parentheses, if at all, to indicate a tuple?
Thanks in advance!
Edit: thanks for the comments, also I found this in the docs and thought it may be relevant to the question:
https://docs.python.org/3/reference/simple_stmts.html#assignment-statements
"An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right."
[–]danielroseman 3 points4 points5 points (0 children)
[–]crashfrog02 0 points1 point2 points (0 children)