Skip to content
Advertisement

Use List Comprehension to get the top n items

I tried:

x = [1,2,3,4,5,6,7,100,-1]
y = [a for a in x.sort()[0:5]]
print(y)
y = y[0:4]
print(y)

but that won’t work because sort() doesn’t return the sorted list

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-d13e11c1e8ab> in <module>
      1 x = [1,2,3,4,5,6,7,100,-1]
----> 2 y = [a for a in x.sort()[0:5]]
      3 print(y)
      4 y = y[0:4]
      5 print(y)

TypeError: 'NoneType' object is not subscriptable

Advertisement

Answer

.sort() sorts the list in-place

list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations)

so you’d have to do this:

x = [1,2,3,4,5,6,7,100,-1]
x.sort()
y = [a for a in x[0:5]]
print(y)
y = y[0:4]
print(y)

Output:

[-1, 1, 2, 3, 4]
[-1, 1, 2, 3]

The difference between .sort() and sorted() in Python.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement