-3

I am wondering if it is possible still use "is" to compare two strings and get true? Like we add some function or expression that makes

F(("a" * 100)) is ("a" * 100)

gets True?

Thanks

Rahul K P
  • 15,740
  • 4
  • 35
  • 52
Fay
  • 105
  • 1
  • 5

2 Answers2

0

The is keyword tests whether two instances are the same. This is a much more strict requirement than equality. In other words, two strings can be equal, but still not be the same. Therefore use == instead.

Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63
0

Yes, but it's not a good idea.

is compares the identities of objects (my_friend is dave), whereas == compares values (my_friend.name == 'dave'). For some data types, they can be used interchangeably, but I wouldn't recommend it

To understand what's happening when you use is, you can use the id() method

>>> foo = 'test'
>>> bar = 'test'
>>> id(foo)
4301978624
>>> id(bar)
4301978624
>>> foo is bar
True

As you can see, Python is returning the same ID for different objects. When objects share the same reference, this means they are, under the hood, the same object, and so foo is bar is True. In the case of our two strings, this kind of behaviour is just because Python is doing internal optimisations for memory and performance reasons, storing one copy of the string in memory and pointing both object references at that same memory.

A great and well known example of this is all numbers <= 256. Python stores a single copy of all these numbers, so when you assign a number <= 256 you simply get a new reference to one of these "global" copies:

>>> foo = 42
>>> bar = 42
>>> id(foo)
4298358768
>>> id(bar)
4298358768
>>> foo is bar
True

Once you get to numbers > 256, Python no longer performs this optimisation and the above behaviour goes away:

>>> foo = 123456789
>>> bar = 123456789
>>> id(foo)
4300144208
>>> id(bar)
4301664016
>>> foo is bar
False

You should only be using is when you want to confirm the identity of a particular object, i.e. that the object you're getting is exactly the one you're expecting. If you use it just to compare values, you'll run into weird and unexpected behaviour because some string comparisons and small integer comparisons will work as expected, but others will most definitely not. If you don't have a specific reason to use is, always, always use ==

daveruinseverything
  • 4,775
  • 28
  • 40