Strange behavior with sort()

Frank Millman frank at chagford.com
Thu Feb 27 07:39:18 CET 2014


"ast" <nomail at invalid.com> wrote in message 
news:530eda1d$0$2061$426a74cc at news.free.fr...
> Hello
>
> box is a list of 3 integer items
>
> If I write:
>
>    box.sort()
>    if box == [1, 2, 3]:
>
>
> the program works as expected. But if I write:
>
>    if box.sort() == [1, 2, 3]:
>
> it doesn't work, the test always fails. Why ?
>

Try the following in the interpreter -

>>> box = [3, 2, 1]
>>> box.sort()
>>> box
[1, 2, 3]

>>> box = [3, 2, 1]
>>>print(box.sort())
None
>>> box
[1, 2, 3]

box.sort() sorts box 'in situ', but does not return anything. That is why 
the second example prints None.

In your second example, you are comparing the return value of box.sort() 
with [1, 2, 3]. As the return value is None, they are unequal.

HTH

Frank Millman






More information about the Python-list mailing list