Python id() Built Function

The id() function in Python is a built-in function that returns a unique id for the specified object. All objects in Python have their own unique id, which is assigned to them when they are created. The id is an integer number that represents the memory address of the object. For example:

>>> x = ('apple', 'banana', 'cherry') # create a tuple object
>>> id(x) # get the id of x
140472391630016

>>> y = 5 # create an integer object
>>> id(y) # get the id of y
140472391630016

>>> z = "geek" # create a string object
>>> id(z) # get the id of z
139793848214784

You can use the id() function to compare two objects and check if they are identical (have the same memory address) or not. For example:

>>> a = 5 # create an integer object with value 5
>>> b = 5 # create another integer object with value 5
>>> c = 6 # create an integer object with value 6
>>> id(a) == id(b) # check if a and b have the same id (are identical)
True
>>> id(a) == id(c) # check if a and c have the same id (are identical)
False

Note that some commonly used data types, such as strings, integers, tuples, etc., may have the same id value if their values are the same. This is because Python caches these objects for performance reasons. 

For example:

>>> s1 = "hello" # create a string object with value "hello"
>>> s2 = "hello" # create another string object with value "hello"
>>> t1 = (1, 2, 3) # create a tuple object with values 1, 2, 3
>>> t2 = (1, 2, 3) # create another tuple object with values 1, 2, 3
>>> id(s1) == id(s2) # check if s1 and s2 have the same id (are identical)
True
>>> id(t1) == id(t2) # check if t1 and t2 have the same id (are identical)
True 

If you want to learn more about Python built-in functions, you can check out some of the web pages on Python id() function.

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions