id()
The id()
function gives a unique number for any object in Python. This number is the location of the object in the computer’s memory. This will be consistent for the duration of the object’s lifetime.
Syntax
id(object)
The parameter, object
, can be any given object such as a string, list, number, dictionary, etc.
Example
In the example below, when two immutable variables are compared using the id()
function, both return the same value pointing to the same location in memory.
This is because immutable objects don’t change. The following example uses an immutable string
object to demonstrate this:
color = 'green'favColor = 'green'print(id(color))print(id(favColor))
This example results in something resembling the following output:
140307997340656140307997340656
Example 2
In this next example, the id()
function will be executed with two mutable variables. Take note of how the function will return different values: two separate unique ids.
This is because mutable objects are able to change. A mutable list
object can be used to demonstrate this:
animals = ['lions', 'tigers', 'bears']favAnimals = ['lions', 'tigers', 'bears']print(id(animals))print(id(favAnimals))
This example results in something resembling the following output:
140279020355392140279020204352
Codebyte Example
The following example displays the output of two immutable number
objects:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours