id() overview
The Python id() function returns the id of an object. The id is a unique integer representing the given object.
A related function of the id() function is the hash() function, which returns a hash value for the given object.
id() on integers
To find the id of an integer, use the id() function as shown below.
# find the id of an integer
myInt = 25
myId = id(myInt)
print(myId)
In this example, the integer value 25 is assigned to the variable myInt.
Then, the id() function is used to find the id of myInt. The result is assigned to the variable myId.
Finally, the id is printed and the result is shown below.
4381396016
id() on float values
To find the id of a float value, use the id() function as shown below.
# find the id of an float value
myFloat = 25.5
myId = id(myFloat)
print(myId)
In this example, the float value 25.5 is assigned to the variable myFloat.
Then, myFloat is passed as argument to the id() function. The return value is assigned to the variable myId.
Finally, the id is printed and the result is shown below.
4472310640
id() on strings
The id() function can be used for strings as shown below.
# find id of a string
myString = 'hello world'
myId = id(myString)
print(myId)
Here, the string 'hello world' is assigned to the variable myString.
Then myString is passed as argument to the id() function and the return value is assigned to the variable myId.
Finally the id is printed and the result is shown below.
4384026096
id() on lists
The id() function can also be used on lists and other iterables.
Please note that the id won't change if the list changes. It keeps the same id as shown below.
# find id of a list
# define myList
myList = [1, 2, 3]
# print id of original list
print(id(myList))
# append integer 4 to myList
myList.append(4)
# print id of appended list
print(id(myList))
In this example, we assign the list [1, 2, 3] to the variable myList.
Then, we print the id of myList using the id() function.
Then, we add the integer 4 to the list.
Finally, the id of the appended list is printed.
As shown below, the id remains the same even though the list has changed.
4473354048
4473354048
id() syntax
The syntax of the id() function is:
id(object)
id() arguments
The id() functions accepts exactly one object as argument.
The object can be an integer, float, string or an iterable.
If more than one object or no object is passed as argument, an TypeError exception is raised.
id() return value
The id() function returns the id of a given object.
The id is returned as an unique integer, which represents the given object.
related functions
A related function of the id() function is the hash() function, which returns the hash value instead of an id.