I tried:
JavaScript
x
6
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)
6
but that won’t work because sort() doesn’t return the sorted list
JavaScript
1
11
11
1
---------------------------------------------------------------------------
2
TypeError Traceback (most recent call last)
3
<ipython-input-21-d13e11c1e8ab> in <module>
4
1 x = [1,2,3,4,5,6,7,100,-1]
5
----> 2 y = [a for a in x.sort()[0:5]]
6
3 print(y)
7
4 y = y[0:4]
8
5 print(y)
9
10
TypeError: 'NoneType' object is not subscriptable
11
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:
JavaScript
1
7
1
x = [1,2,3,4,5,6,7,100,-1]
2
x.sort()
3
y = [a for a in x[0:5]]
4
print(y)
5
y = y[0:4]
6
print(y)
7
Output:
JavaScript
1
3
1
[-1, 1, 2, 3, 4]
2
[-1, 1, 2, 3]
3