Strange behavior with sort()

A

ast

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 ?

Thx
 
F

Frank Millman

ast said:
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 -
[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
 
E

Eduardo A. Bustamante López

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 ?

Thx

Because when you call the .sort() method on a list, it does the sort
in-place, instead of returning a sorted copy of the list. Check this:

The method does not return a value, that's why the direct comparison
fails.

What you might want is to use the sorted() method on the list, like
this:
sorted([2,1,3]) [1, 2, 3]
sorted([2,1,3]) == [1,2,3]
True
 
M

Marko Rauhamaa

ast said:
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
 
G

Gary Herron

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]:

Most such questions can be answered by printing out the values in
question and observing first hand what the value is.

So, print out box.sort() to see what it is. You might be surprised.

Hint: box.sort() does indeed cause box to be sorted, and the sorted list
is left in box, but the sorted list is not returned as a function value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top