Strange behavior with sort()
orgnut at yahoo.com
Thu Feb 27 08:23:29 CET 2014
On 02/26/2014 10:24 PM, ast wrote:
> box is a list of 3 integer items
> If I write:
> 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 ?
sort() sorts the sequence in place, but it _returns_ None.
Your second example becomes the equivalent of:
if None == [1, 2, 3]:
So although your box does become sorted, it is NOT what is compared in your if statement.
BTW, the sorted() function won't work here either. It will return the sorted sequence, but it
leaves the original unchanged.
-=- Larry -=-
More information about the Python-list