[Tutor] How memory works in Python

Deepak Dixit deepakdixit0001 at gmail.com
Wed Jan 8 05:49:06 EST 2020


As you can see in the code, we are getting different location for tuple
which is also immutable. So it should not be dependent on type of variable.

Anyway, Thanks for your help.

On Wed, Jan 8, 2020, 3:58 PM Cal97g . <cal.97g at gmail.com> wrote:

> What is happening is that python sees you have some small variables which
> are identical. As these variables are immutable python knows they cannot be
> changed.
>
> Instead of creating a new memory location for each variable, python
> references the same memory location for both items.
>
> This is why your the id for (x1, y1) + (x2, y2) is identical.
>
> Many Thanks
>
> Callam Delaney
>
>
> On Tue, 7 Jan 2020 at 14:45, Deepak Dixit <deepakdixit0001 at gmail.com>
> wrote:
>
>> Hi Team,
>>
>> I was thinking on the memory management in Python but little confused here
>> because when I assign same value of type number and string to different
>> variable, it points to same memory but when I do it for list or tuple it
>> points to different memory locations.
>>
>> Here is the code and the output:
>>
>> # test.py
>> x1 = 10
>> y1 = 10
>>
>> x2 = "Hello"
>> y2 = "Hello"
>>
>> x3 = [10]
>> y3 = [10]
>>
>> x4 = (10,)
>> y4 = (10,)
>>
>> print id(x1) == id(y1)
>> print id(x2) == id(y2)
>> print id(x3) == id(y3)
>> print id(x4) == id(y4)
>>
>> deepak at Deepak-PC:~$ python test.py
>> True
>> True
>> False
>> False
>>
>>
>> Can you help me to understand how it works?
>> --
>>
>>
>> *With Regards,*
>> *Deepak Kumar Dixit*
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>


More information about the Tutor mailing list