+ 3
Confusion with list and variable
Why in this code when I add 1 to y, x is not increased? But when I append something to c, in d it is also appended. Though in both cases I defined a single object with two reference and also I stated that references are same ( c = d and x = y ) Also why a and b both are not changed when I append something to one of them and same question for p and q. What is the underlying concept between all of these things happening? Can anybody explain in details or suggest me a good read? https://code.sololearn.com/c56DlH8Ee2bR/?ref=app
8 ответов
+ 6
Another factor that might be confusing and is therefore worth mentioning:
Id tests may fail you with immutable objects!
For example look at this:
a = [1, 2, 3]
b = [1, 2, 3]
for x, y in zip(a, b):
print(id(x), id(y))
You will see that although we create two new lists with a separate set of numbers, the ints in both lists are identical!
Scandalous!
The reason:
With immutable objects it makes really no difference if you make a new zero each time or just put a reference of the same zero into another list.
You can't change them anyway, so it doesn't matter if they're one or many.
On the other hand, with mutable objects like lists it's essential that you know if you're dealing with a twin of that list or the actual list - you don't want to erase stuff from the wrong one!
Therefore, implementations of Python are allowed to internally handle the identities of immutable objects whichever way they like, for example storing just one zero for memory reasons, but have to stick to the rules with mutable ones.
+ 6
It was a huge discussion!😂😂
♤♢☞ 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 ☜♢♤ do you remember
https://www.sololearn.com/discuss/2338606/?ref=app
+ 4
The immutable versus mutable is the right hint.
Immutable types return a new object whenever you do something that looks like you change an object.
The operator overloads make it somewhat hard to see what exactly they are doing.
You know, even if you write +=, what really happens may be quite different.
For example, += with lists is basically the same as calling extend on that list.
a = [1, 2]
a.extend([3, 4])
... would be equivalent to...
a += [3, 4]
With an int...
a = 41
a += 1
... is more like...
a = a + 1
So in the first case you change an object, in the second case, you make a new one.
+ 3
♤♢☞ 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 ☜♢♤ thank you. This tutorial is very good. I will read it again and try to understand what is going on.
+ 2
codemonkey thank you. It's really tricky. I am getting lost while declaring new variables. I will try to learn more about mutable and immutable.
+ 2
HonFu thanks a lot for explaining it. ^_^