Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Python Lists mutable?

When I type following code,

x=[1,2,4]
print(x)
print("x",id(x))
x=[2,5,3]
print(x)
print("x",id(x))

it gives the output as

[1, 2, 4]
x 47606160
[2, 5, 3]
x 47578768

If lists are mutable then why it give 2 memory address when changing the list x?

like image 226
amandi Avatar asked Jun 18 '14 17:06

amandi


People also ask

Are lists mutable or immutable?

List of Mutable and Immutable objects. Objects of built-in type that are mutable are: Lists.

Is list a mutable type in Python?

List, Sets, and Dictionary in Python are examples of some mutable data types in Python. Immutable data types are those, whose values cannot be modified once they are created. Examples of immutable data types are int, str, bool, float, tuple, etc.

Can a list be mutable?

Unlike strings, lists are mutable. This means we can change an item in a list by accessing it directly as part of the assignment statement. Using the indexing operator (square brackets) on the left side of an assignment, we can update one of the list items.

What are list list are mutable in Python?

A list refers to a data structure in Python that is an ordered sequence of elements and it is mutable in nature. Furthermore, Python mutable lists may involve various data types like objects, integers and strings. Moreover, the lists, due to their mutable nature, can be altered after their creation.


1 Answers

You created a new list object and bound it to the same name, x. You never mutated the existing list object bound to x at the start.

Names in Python are just references. Assignment is binding a name to an object. When you assign to x again, you are pointing that reference to a different object. In your code, you simply created a whole new list object, then rebound x to that new object.

If you want to mutate a list, call methods on that object:

x.append(2)
x.extend([2, 3, 5])

or assign to indices or slices of the list:

x[2] = 42
x[:3] = [5, 6, 7]

Demo:

>>> x = [1, 2, 3]
>>> id(x)
4301563088
>>> x
[1, 2, 3]
>>> x[:2] = [42, 81]
>>> x
[42, 81, 3]
>>> id(x)
4301563088

We changed the list object (mutated it), but the id() of that list object did not change. It is still the same list object.

Perhaps this excellent presentation by Ned Batchelder on Python names and binding can help: Facts and myths about Python names and values.

like image 57
Martijn Pieters Avatar answered Sep 30 '22 08:09

Martijn Pieters