Python 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.
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 CoursesIncludes 6 Courses
- With Professional CertificationWith Professional Certification
- Beginner Friendly.75 hours75 hours
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 CoursesIncludes 27 Courses
- With Professional CertificationWith Professional Certification
- Beginner Friendly.95 hours95 hours
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))Copy to clipboardCopy to clipboard
This example results in something resembling the following output:
140307997340656140307997340656Copy to clipboardCopy to clipboard
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))Copy to clipboardCopy to clipboard
This example results in something resembling the following output:
140279020355392140279020204352Copy to clipboardCopy to clipboard
Codebyte Example
The following example displays the output of two immutable number objects:
Visit usVisit usCodeHide codeOutputHide outputCopy to your clipboard
All contributors
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 CoursesIncludes 6 Courses
- With Professional CertificationWith Professional Certification
- Beginner Friendly.75 hours75 hours
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 CoursesIncludes 27 Courses
- With Professional CertificationWith Professional Certification
- Beginner Friendly.95 hours95 hours
