Python - ÔÇŁis" and tuples | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

Python - ÔÇŁis" and tuples

Why is third output "False"? def maxmin(arr): return max(arr), min(arr) arr = [8,9,4,6,1] Mm1 = maxmin(arr) Mm2 = maxmin(arr) print(Mm1) print(Mm2) print(Mm1 is Mm2) print(type(Mm1)) print(type(Mm2))

12th Mar 2020, 6:45 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
5 Antworten
+ 4
Paolo, you can see that Mm1 and Mm2 are different objects with different object id's by modifying the print statement: ... print(Mm1, id(Mm1)) print(Mm2, id(Mm2)) ...
12th Mar 2020, 8:16 PM
Lothar - avatar
+ 4
The specification says that immutable types in Python, if they are equal, *can* fall together as just one value (and thereby one id). In that case, a 'is' b would return True. But they could also be two objects. It could be different in different situations, and it could definitely be different between two implementations of Python. If they remain separate, a 'is' b would be False. Why's it like that? Because with immutable types it doesn't matter if you store several or only one - you can't change them anyway. So while asking for this can be an interesting party game, actually the practical answer is: Why do you even care? Identity is only important for mutable objects! There it does matter, and there you normally experience no surprises with your 'is' tests.
12th Mar 2020, 11:29 PM
HonFu - avatar
+ 3
'is' means identity aka memory address of object. Mm1 and Mm2 value will be same which is 9. But memory address will be difference because '9' is immutable type. That means 9 will be copied (addresses will also be different, right?) when assigning to Mm1 and Mm2 variables. Hope it helps :)
12th Mar 2020, 6:57 PM
The Sylar
+ 2
Is pointing diferent objects ( booth are new)
12th Mar 2020, 11:02 PM
guillem ardanuy
guillem ardanuy - avatar
+ 1
I think a main reason "False" is definition. Because: tuple_a = (12, 34) tuple_b = (12, 34) print(tuple_a is tuple_b) # return True print("adress:", id(tuple_a)) print("adress:", id(tuple_b))
15th Mar 2020, 8:12 PM
Valerii Mamontov
Valerii Mamontov - avatar