Computer Science, asked by BeastBoY007, 9 months ago

in python, why is 'goodbye' < 'hello' true

Answers

Answered by mrudul44
0

Answer:

Consider the following (Python 2.7.3, 64bit):

>>> a = "Hello"

>>> b = "Hello"

>>> a is b

True

Python interns the short string 'Hello', storing it only once. This is an implementation detail and is not guaranteed by the language standard. It may fail on longer strings:

>>> a = "this is a long string"

>>> b = "this is a long string"

>>> a is b

False

Now consider this:

>>> a = ["Hello"]

>>> b = ["Hello"]

>>> a is b

False

a and b are two different objects. You can check this with id():

>>> id(a)

33826696L

>>> id(b)

33826952L

This is a Good ThingTM because when you do

>>> a[0] = "Goodbye"

>>> a

['Goodbye']

>>> b

['Hello']

However, if you do

>>> a = ["Hello"]

>>> b = a

>>> a is b

True

>>> a[0] = "Goodbye"

>>> b

['Goodbye']

because a and b are names that refer to the same object (id(a) == id(b)). Finally, to show that even though you get

>>> a = ["Hello"]

>>> b = ["Hello"]

>>> a is b

False

the strings are still interned and stored only once:

>>> id(a[0])

33846096L

>>> id(b[0])

33846096L

Mark as Brianlest

Similar questions