Comparison numbers in list

Question:

My question sounds retty stupid, but I really can’t understand and solve this.

I try to find the biggest number in the list. There’re only two numbers, my code:

list = ['7', '10']

a = list[0]
b = list[1]
if a > b :
    print('a')
else :
    print('b')

When I run it I get ‘a’, but why?

Asked By: ctrl

||

Answers:

You have problems with used data types. Both list values are strings, not integers. When comparing string values you are trying to compare characters starting from left.

So when comparing ‘7’ and ’10’ computer first compares first chars of each string by its unicode values, so ‘7’ and ‘1’. And because 1 (unicode 49) is less than 7 (unicode 55), you receive this result.

So you need to either change the list items type to integer:

list = [7, 10]

or cast values to integer before comparing:

a = int(list[0])
b = int(list[1])

You could convert your list to int, then use build in max function. This approach is better when the size of the list is dynamic

int_list = [int(x) for x in list]
print(max(int_list))
Answered By: Beri
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.