Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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
like image 806
Baldau dhanoriya Avatar asked Jul 15 '26 13:07

Baldau dhanoriya


2 Answers

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]))
like image 158
Mureinik Avatar answered Jul 18 '26 23:07

Mureinik


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]
ods.sort()
print(ods[0])
like image 27
StPiere Avatar answered Jul 19 '26 01:07

StPiere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!