简体   繁体   中英

Can't understand mutable objects in python

So I thought that lists were MUTABLE objects in python so they could be changed.

When I create a list:

list = [1, 2, 3]
print(id(list))
list = [4, 5, 6]
print(id(list))

I should get the same ID in both cases.. But I got different one. Why is that?

The operator = with just a name on the left hand side always assigns an object to the name. It does not do anything else.

The operation = with a name that has an index (something in brackets) calls __setitem__ on the named object.

You are invoking the first behavior. You are creating a new list, discarding the old one, and assigning the new one to the name list .

To mutate the object instead of replacing, you'll want to invoke the second behavior:

lst[:] = [4, 5, 6]

This assigns the new values to the elements of the original list. Now the contents of the original list will change, but it will be the same object with the same id, as you expected.

In both cases, a new list object is created any time you put a comma-separated list in square brackets. [1, 2, 3] creates a list and so does [4, 5, 6] . The difference is in what you do with the second list. lst = [4, 5, 6] assigns it to the name lst , discarding any previous object that name may have been bound to. lst[:] = [4, 5, 6] is actually roughly equivalent to doing lst.__setitem__(slice (None), [4, 5, 6]) . This copies the elements of the second list into the first, but doesn't alter any name bindings.

And don't call a variable list . It shadows a builtin function. There's nothing fundamentally to prevent you from doing this, it's just rebinding a new object to an existing name (like your original example). But then you'll want to use the list function, and join the hordes on Stack Overflow always asking why their builtins don't work.

In the second line, you are just creating a new list object and assigning it to list.

list=[4,5,6] //creates a new list object and puts its reference in list

To show that list are mutable, you can try applying operations on this line:

list=[1,2,3]

Like:

>>> a = [1,2,3]
>>> id(a)
2814816838216
>>> a[0] = 4
>>> a
[4, 2, 3]
>>> id(a)
2814816838216

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