Python id() Function



The python id() function is used to obtain the unique identifier for an object. This identifier is a numeric value (more specifically an integer) that corresponds to the object's memory address within the Python interpreter at any given time.

An id is assigned to an object at the time of its creation and each object is assigned a unique ID for identification. Each time we run the program, a different id will be assigned. However, there are some exception too.

In the next few section, we will be learning more about this function.

Syntax

The following is the syntax for the Python id() function.

id(object)

Parameters

The python id() function accepts a single parameter −

  • object − This parameter specifies an object for which an ID is to be returned.

Return Value

The Python id() function returns an unique ID of integer type.

Examples

Now, let's understand the how the id() function works with the help of examples −

Example 1

The following is an example of the Python id() function. In this, are trying to find the ID of an integer value.

nums = 62
output = id(nums)
print("The id of number is:", output)

On executing the above program, the following output is generated −

The id of number is: 140166222350480

Example 2

The following example shows how to display the unique ID of a string. We simply need to pass the string name to the id() function as an argument.

strName = "Tutorialspoint"
output = id(strName)
print("The id of given string is:", output)

The following is the output obtained by executing the above program −

The id of given string is: 139993015982128

Example 3

No two objects can be assigned with the same IDs. In this example, we are creating two objects and then we are checking whether their IDs are equal or not. If they are equal, the code will return true otherwise, false.

numsOne = 62
numsTwo = 56
resOne = id(numsOne)
resTwo = id(numsTwo)
print("The id of the first number is:", resOne)
print("The id of the second number is:", resTwo)
equality = id(numsOne) == id(numsTwo)
print("Is both IDs are equal:", equality)

The following output is obtained by executing the above program -

The id of the first number is: 140489357661000
The id of the second number is: 140489357660808
Is both IDs are equal: False

Example 4

A unique identifier or ID is also assigned to the object of a class. Here, we are illustrating the same.

class NewClass:
   pass

objNew = NewClass()
output = id(objNew)
print("The id of the specified object is:", output)

The above program, on executing, displays the following output -

The id of the specified object is: 140548873010816
python_built_in_functions.htm
Advertisements