I am a python beginner. Recently I saw this snippet of code:
>>> words = ['I', 'turned', 'off', 'the', 'spectroroute']
>>> words[2], words[3], words[4] = words[3], words[4], words[2]
>>> words
['I', 'turned', 'the', 'spectroroute', 'off']
I am confused about the 2nd line. It seems tuples are used but I don’t understand why the sequence of the list is changed to the result?
It looks like the 2nd line is doing this:
>>> tmp = words[2]
>>> words[2] = words[3]
>>> words[3] = words[4]
>>> words[4] = tmp
My question is: why does the code in 2nd line change the list as the result?
Thanks in advance
You are pretty much correct. Its creating a tuple on the right side (in memory) and then unpacking its values into the original list, thus overwriting the previous indexes. Thats why you dont need a tmp variable, since its happening in memory.
Its similar to this concept: