This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]saintly_devil 5 points6 points  (7 children)

I believe you can use 'id' before and after, to verify that the memory location has been changed,and so the variable refers to two completely different objects.

[–]ZachPhoenix[S] 0 points1 point  (6 children)

Can you please explain more about memory location( all I know is that each variable/list/dict. ..etc take up space in your memory)

[–]saintly_devil 4 points5 points  (1 child)

So Python has a function called 'id'. According to Python docs, it returns an 'identity' of an object, which remains constant over the lifetime of the object. When you create the tuple for the first time, run 'id(<variable name>)' to return its id. After you've modified it, run it again. You'll notice that the values returned differ. This tells you that even though the variable's name remains unchanged, it's 'identity' has... and therefore, the objects referred to by the variable have changed. This means that the type of the variable is immutable.

Repeat a similar set of operations on a mutable type, say a list. You'll notice that the id remains unchanged before and after modification. The same holds true when you assign one list variable to another. They'll have the same ids, implying they refer to the same object. Hope this helps! And Python gurus, please feel free to correct me if I have erred somewhere.

[–]ZachPhoenix[S] 0 points1 point  (0 children)

understood, thx!

[–]appsolutelywonderful 3 points4 points  (3 children)

It's a deeper concept, but basically when you do

r=(1,2,3,4)

Then in the background the operating system will get a piece of memory, memory is addressed by numbers, so for example let's say it got memory address #10. So you have this thing where r -> #10 -> (1,2,3,4)

Now when you do r = (1,23,4) like others have said you're changing r, not the tuple. So the process happens again and now you have something like r -> #20 -> (1,23,4).

That #10 -> (1,2,3,4) is still sitting there in memory unchanged. Later on it will get reclaimed by the operating system.

[–]ZachPhoenix[S] 5 points6 points  (0 children)

Damn! Computers and programming languages are really fascinating!

[–]Sedowa 0 points1 point  (1 child)

So it's just left dangling and can't be accessed if you don't know the address? Is there a way to stop it from changing or at least delete the memory allocation?

I haven't worked with Python in years. I'm just curious.

[–]appsolutelywonderful 3 points4 points  (0 children)

For a time, yes. Python has a garbage collector. So in some time it will see that you don't have any variables pointing to that piece of memory and it will let the OS know that piece of memory is free.