Search code examples
sortingpython-3.7nonetype

'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

Solution

  • 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]))