lettura simple

Object Identities in Python

When you bring an object into existence in Python, it is given a unique identity number.

So, what exactly is an 'identity'? In Python, everything is an object - from numbers to strings, lists to tuples. Every object in Python carries a unique identity, a defining feature that sets it apart from the rest. This identity comes in the form of an integer number, otherwise known as the object's ID. It's a number that unmistakably marks the object in the program.

To reveal an object's identity, you can use the id() function:

id(oggetto)

Here's a practical example for you.

First, create two string type objects and assign them to two separate variables. Let's name them myVar1 and myVar2.

>>> myVar1="Hello World"
>>> myVar2="Ciao"

Type id(myVar1) to display the identity of the first object.

>>> id(myVar1)
140457824779760

Next, show the identity of the second object by typing id(myVar2).

>>> id(myVar2)
140457825312368

The two variables contain the same data type (string), but have different identities since they are distinct objects.

The variable myVar1 holds the string "Hello World", while myVar2 holds the string "Ciao".

Note. The strings "Hello World" and "Ciao" are distinct, making them separate objects.

Now, let's create two variables with identical contents.

For instance, assign the string "Hello World" to both myVar1 and myVar3.

>>> myVar1="Hello World"
>>> myVar3="Hello World"

Type id(myVar1) to display the identity of the first object.

>>> id(myVar1)
140457824779760

Type id(myVar3) to display the identity of the third object.

>>> id(myVar3)
140457824779760

In this case, Python returns the same identity (140457824779760) for both variables, as they hold the same object - the string "Hello World".

example of identities in Python

Now, let's talk about why identities matter.

Object identities allow Python to handle computer memory more efficiently.

Python employs a memory management system based on references rather than values.

This means that two variables with different names could point to the data stored at the same memory address.

For example, the variables myVar1 and myVar3 contain the same string "Hello World". Rather than using two separate memory addresses, Python utilizes just one. Both variables myVar1 and myVar3 are given the same reference, which is a link to a single memory address.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin