-1

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
nicomp
  • 4,344
  • 4
  • 27
  • 60
  • https://stackoverflow.com/questions/4215472/python-take-max-n-elements-from-some-list – Cory Kramer Apr 13 '21 at 14:11
  • 1
    Why do you want to use list comprehension for this? Does not seem like an appropriate use. Why not simple sort and then first 5 items? – lllrnr101 Apr 13 '21 at 14:12
  • `y = sorted(x, reverse=True)[:5]` – 001 Apr 13 '21 at 14:14
  • 'Cause I'm doing other things in the LC expression and LC is super cool and I want to be a Pythonista. ;) – nicomp Apr 13 '21 at 14:17
  • 2
    part of being a good Python programmer is knowing when to use certain things and when not to. simply indexing a list is not a good use of LC. – gold_cy Apr 13 '21 at 14:27

1 Answers1

1

.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.

baduker
  • 19,152
  • 9
  • 33
  • 56