+ 3
is keyword in python
What exactly does the keyword 'is' do? Could you give me some examples with explanation? Thank you for answers.
3 Respostas
+ 10
It means the same point of reference, the same memory block pointer. Two variables can be equal but not identical, occupying different memory locations. But when two variables point to the same memory location, they are identical and changing one affects the other, too.
A good example is with lists:
a = [1, 2, 3]
b = [1, 2, 3]
a is equal to b, a a==b returns True. But they are just two separate lists with equal values inside. If you change a[0] = 0, b[0] will stay equal to 1.
Now:
a = b
a was assigned the same memory location, as b. If you change a[0] = 5, print(b[0]) will also display 5.
So not only a == b, but even more: a is b
0
but what means identity?
0
Identity it can be said that it is the 'id' of the variable
for example:
a = []
b = []
print( id(a) ) # Outputs: 20134128
print( id(b) ) # Outputs: 20134168
print( a is b ) # Outputs: False, different ids
print( a == b ) # Outputs: True, equal values, a = [], b =[]
As Kuba says, two variables can be equal but not identical, occupying different memory locations.
I hope you understand.