Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
min(list) ..?
#1
Hi guys,

I have a little question. Hopefully that somebody can help me :) :
If I have this list:
L=['13', '2', '3', '3', '5', '7']
min(L) return '13'.

Why 13 and not 2 ?

Thank you !
Reply
#2
This is because you have a list of strings, not integers
try:
list_of_ints = [13, 2, 3, 5, 7]
print(min(list_of_ints))
Reply
#3
Strings are compared lexicographically - character by character - till the bigger/smaller is defined. That means that "2" is larger than "13", because the first character of the string "2" is bigger than the first character of the string "13"

You could use the named argument key of the min function to get the result
min(L, key=int)
The result in the string form, but values are compared by their integer equivalent

Output:
In [64]: L=['13', '2', '3', '3', '5', '7'] In [65]: min(L, key=int) Out[65]: '2'
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#4
Thank you guys for your responses ! :)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020