简体   繁体   中英

How Does Python Swap Elements inside a List?

I am new to Python, and just learned about mutable and immutable objects. It appears that when we are swapping elements inside a list, Python creates copies of the individual elements and then copy them back into the list.

在此处输入图片说明

In the above example, we begin with n = [[1, 2], [3, 4]] . The first sublist, [1, 2] occupies ID# 24 , and the second sublist [3, 4] occupies ID# 96 . At first, I thought that since lists are mutable, after swapping, ID# 24 holds [3, 4] and ID# 96 holds [1, 2] . But as we can see in the test above, that is not the case. Rather, Python is pointing to the objects in a manner determined by our swap; the first slot of the list points to 96 and the second slot points to 24 .

Certainly, the ID# of n did not change, so n did not violate the definition of a mutable object. But the way the sublists got swapped seems to be a caveat. Can you kindly confirm or explain in more precise language?

You are mistaken about IDs. The ID#24 is the ID of the list [1,2] . It is NOT the memory address or ID of index 0 in n .

You might want to try an example like this to confirm:

>>> x = [1, 2]
>>> id(x)
4332120256
>>> l = [x, 3]
>>> id(l[0])
4332120256
>>> 

From the documentation :

Assignment of an object to a target list is recursively defined as follows.

If the target list is a single target: The object is assigned to that target. If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

If you read that closely, you'll see that you have the scenario:

target_list = expression_list

The expression list is evaluated first , and evaluates into a tuple:

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)

So if you have:

a = [1, 2]
a[1], a[0] = a[0], a[1]

It is effectively like writing the following:

a = [1, 2]
temp = (a[0], a[1]) # Expression list evaluates to tuple.

# target_list assignment to corresponding elements from expression list.
a[1] = temp[0]
a[0] = temp[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM