Python id () function

libertycodervice

libertycodervice

Posted on March 2, 2020

Python id () function

Python stores all of its data in the computers memory. The memory is a block that is divided into sub blocks, where each block has an address.

memory address

In Python, the id() function is used to obtain the memory address of the object.

Because Python is a high-level programming language, you usually don't need memory addresses. The value can be any variable, including a string.

The syntax of the id() function is:

    id([object])

The parameter it takes is the object. It returns the memory address of the object. Conceptually it's the same as a memory address in C, but depending on the implementation of Python it may not be.

Examples

The following examples show id to use:

>>> x = "python"
>>> id(x)
139738512291632
>>> y = "programming"
>>> id(y)
139738511022192
>>> 

Python is quite smart with memory. If the value is the same, it will use the same memory address

>>> x = 10
>>> y = 10
>>> z = 10
>>> id(x)
9302464
>>> id(y)
9302464
>>> id(z)
9302464
>>> 

These all point to the same location in memory, which is why their values are the same.

If the values are unique, the memory addresses will be different, because they point to different locations in memory:

>>> x = 10
>>> y = 11
>>> z = 12
>>> id(x)
9302464
>>> id(y)
9302496
>>> id(z)
9302528
>>> 

Related links:

💖 💪 🙅 🚩
libertycodervice
libertycodervice

Posted on March 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024