I cannot understand why the a1
, b1
variables refer to the same thing, but a2
, b2
do not refer to the same thing:
a1="abc123"
b1="abc123"
print(a1 is b1)
Output:
True
a2="+abc123"
b2="+abc123"
print(a2 is b2)
Output:
False
I cannot understand why the a1
, b1
variables refer to the same thing, but a2
, b2
do not refer to the same thing:
a1="abc123"
b1="abc123"
print(a1 is b1)
Output:
True
a2="+abc123"
b2="+abc123"
print(a2 is b2)
Output:
False
a2="+abc123"
b2="+abc123"
print(a2 is b2)
it says True You may be leaving some empty space
You misunderstood what the is
operator tests. It tests if two variables point the same object, not if two variables have the same value.
From the documentation for the is operator:
The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.
I suggest you use the equality operator(==
)
Here is how to use the equality operator for your scenario:
a2="+abc123"
b2="+abc123"
print(a2 == b2)
Output:
True
If you use the id()
operator witch Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for every object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
Test for b1's id
id(a2)
Output:
1600416721776
Test for b2's id
id(b2)
Output:
1600416732976
Using the id()
operator you can see that they do not point to the same object
It is worth a mention that the it is a bad idea to use the is
operator for strings because Alphanumeric string's always share memory and Non-alphanumeric string's share memory if and only if they share the same block(function, object, line, file):
Alphanumeric string's:
a='abc'
b='abc'
print('a is b: ' a is b)
Output:
a is b: True
non-Alphanumeric string's:
A='+abc123'; B='+abc123';
C='+abc123';
print('A is B: 'A is B)
print('A is C: 'A is C)
Output:
A is B: True
A is C: False