'NoneType' object is not subscriptable in python

#i'm just testing it 

lst=[3, 2, 4, 5,1]

print([i for i in lst if i % 2 != 0].sort()[0])

#i haven't tried any thing        

#I expect the output 1

sort() sorts a list in place and returns None. Looks like you meant to use sorted instead:

print(sorted([i for i in lst if i % 2 != 0])[0])

Note, however, there's no need to sort the list if you just take its first element. You could use min instead for the same result with a better performance (O(n) instead of O(nlog(n)):

print(min([i for i in lst if i % 2 != 0]))

sort() is modifying method and returns None

This one works:

lst=[3, 2, 4, 5,1]
odds = [i for i in lst if i % 2 != 0]

The problem here is, when you run the 'sort' function on a list, this function updates the list and returns void. So you really are trying to call a index on a NoneType object.

The best way to solve this problem is setting the filter to a variable, run the sort on this var and after this, print the value that you want to.


l = [i for i in lst if i % 2 != 0]



  • #i haven't tried any thing -- I suggest that you do: remove the [0] and see what type the expression has (you can use type for that or just print).
  • Or use sorted like this heheheh