-1

I just started python and I understand that when you set a variable equal to a object type like a string, it will make them equivalent but I want to know why is 'abc' == 'abc' True, does it check the memory location of both strings and see that they have the same location? Or does python check the actual inside of the string to see if each character matches the other?

I know this is a basic python question and I understand why the code outputs the results we see, but I want to know how python checks equality when you are just working with data types with the same construct.

'abc' == 'abc' #Output is True
'ab' == 'abc' #Output is False
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • It's the latter of the two options you gave. This has [already been asked](https://stackoverflow.com/questions/43466106/what-happens-when-you-compare-two-strings-in-python) – ketcham Jun 20 '19 at 20:05

1 Answers1

0

The equality operator == checks for equality. Are a and b the same string?

a = [1,2,3]
b = [1,2,3]
a == b  # True
a is b  # False

There is an is keyword that will check the memory location.

a = [1,2,3]
b = [1,2,3]
a is b # False
c = a
a is c  # True

It is worth noting that strings work a bit differently when used with the is keyword.

a = '123'
b = '123'
a == b  # True
a is b  # True

EDIT: From @Barmar "The reason for the last result is that immutable objects are interned, so it doesn't make multiple copies of equivalent strings."

Kevin Welch
  • 1,488
  • 1
  • 9
  • 18