redwood_gm
redwood_gm

Reputation: 363

sort() in python does not completely work as expected

If l is a list, say [9,3,4,1,6], I know that l.sort() will sort the list in place. I also know that m=sorted(l) will create a new list, m, as a sorted version of l.

What I don't understand is why m=l.sort(), does not create m as a sorted version of l, since this appears to be an assignment of a sorted list to m. The problem can be seen from the following

In [37]: l = [9,3,4,1,6]

In [38]: m=l.sort()

In [39]: m

In [40]: type(m)
Out[40]: NoneType

Of course if I do the following, m becomes a sorted version of l

In [41]: l = [9,3,4,1,6]

In [42]: l.sort()

In [43]: m=l

In [44]: m
Out[44]: [1, 3, 4, 6, 9]

Can someone explain why m=l.sort() doesn't work as an assignment?

Upvotes: 0

Views: 104

Answers (3)

Olivier Melançon
Olivier Melançon

Reputation: 22324

list.sort mutates your list to sort it, it does not return a new one.

l = [9, 3, 4, 1, 6]
l.sort()
l # [1, 3, 4, 6, 9]

If you want to create a new sorted list, use sorted.

l = [9, 3, 4, 1, 6]
m = sorted(l)
l # [9, 3, 4, 1, 6]
m # [1, 3, 4, 6, 9]

Upvotes: 2

Sumit S Chawla
Sumit S Chawla

Reputation: 3600

sort() works directly on the list and has a None return type. So, if you want to assign it to some variable and keep the original list, you can do it the following way:

l = [9,3,4,1,6]
m = sorted(l)
print(m)

Output:

[1, 3, 4, 6, 9]

It will keep the original list as it is.

Upvotes: 0

Umer Amjad
Umer Amjad

Reputation: 68

l.sort() has no return value (see here), so when you do

m = l.sort() 

you're assigning m to nothing

Upvotes: 1

Related Questions