0

I am perplexed at the behavior of python code below. I want to sort last 3 numbers in a list. But when I chain the operations, it doesn't work. What am I missing?

Behavior 1:

>>> a = [10,4,2,3]
>>> b = a[1:].sort() # I want to sort last 3 numbers. But when I chain the 
                     # operations, it doesn't work. Why?
>>> b
<empty value> 

====

Behavior 2:

>>> a = [10,4,2,3]
>>> b = a[1:]
>>> b.sort()
>>> b
[2, 3, 4]
  • 4
    It is _legal_ but it's useless. `.sort()` works _in place_ and returns `None` so it's useless in an assignment. `b = ...` in `b = a[1:].sort()` is an assignment, so you get `None` back. Look into `sorted()` – roganjosh Nov 19 '19 at 23:35
  • 2
    Instead, you can do `b = sorted(a[1:])`. See: https://stackoverflow.com/a/22442440/11981207 – Kei Nov 19 '19 at 23:38
  • I agree. But if I execute a[1:].sort() then this does not sort "a" which is how the whole investigation started. – Suhas Patil - SWTest Architect Nov 20 '19 at 01:57

1 Answers1

2

This is because .sort() does not return a new list but rather mutates the existing list. E.g. [5, 2, 7, 4, 5].sort() does not return anything. Take a look at this:

a = [2, 4, 7, 3, 4, 6]
a.sort()
print(a)

The output is:

[2, 3, 4, 4, 6, 7]

What you might want to do is this:

a = [2, 4, 7, 3, 4, 6]
b = sorted(a[1:])
print(a)
print(b)