Strange behavior with sort()

Marko Rauhamaa marko at pacujo.net
Thu Feb 27 01:41:57 EST 2014


"ast" <nomail at invalid.com>:

> if I write:
>
>    if box.sort() == [1, 2, 3]:
>
> it doesn't work, the test always fails. Why ?

The list.sort() method returns None.

The builtin sorted() function returns a list:

   if sorted(box) == [1, 2, 3]:

would work.

Note that the list.sort() method is often preferred because it sorts the
list in place while the sorted() function must generate a fresh, sorted
list.


Marko



More information about the Python-list mailing list