Use id() to understand list and immutable in Python

Tobby Kuo
2 min readFeb 22, 2019

--

Python id() function

Here is the explanation of id() in w3schools:

The id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created. The id is the object’s memory address, and will be different for each time you run the program.

From the explanation above, there are somethings we need to notice:

  1. It’s important to note that everything in Python is an object, even integers and Classes. So if you run id(123) you will still get an integer represent its id.
  2. The integer returned by id() represents an object’s memory address, so we can use this integer to check if two object point to a same address.

Python list object and id()

The list object in python is very similar to array in other languages. They all have some methods liked insert, pop, remove, index …etc. You also can read and write a specific position in list with constant time. But if you use id() function to look up items in list, you’ll find the biggest difference between list and array:

The address of items in list are not continuous! A usual Array use continuing positions in memory to store data, but a list in python doesn’t.

Actually, a list in python is implemented by an arrays of pointers which point to the list elements.

immutable

Everything is an object in python, and each have these attributes:

  • identity: To represent the memory address for this object. You can get the identity from the id() method mentioned above. Once an object is created, you can’t change its identity.
  • type: To represent the type of this object. You also can get it from the type() method. Again, Once an object is created, you can’t change its type.
  • value: To represent the data or the value in this object. Different from identity and type, some object’s value can be changed. We call these kind of objects ‘mutable’, and ‘immutable’ for those can not change value.’

So, what common types are mutable and immutable in python?

immutable objects:

  • Numeric types: int, float, complex
  • string
  • tuple

mutable objects:

  • list
  • dict
  • set

We can show that list is mutable by using id():

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

Or show that int is immutable:

>>> a = 1
>>> id(a)
4470587440
>>> a = 2
>>> id(a)
4470587472

reference: http://wsfdl.com/python/2013/08/14/%E7%90%86%E8%A7%A3Python%E7%9A%84mutable%E5%92%8Cimmutable.html

--

--

Tobby Kuo

Microsoft Software Engineer, focus on infrastructure developments for big data in distributed environments.