Search code examples
pythonstringintegerminnested-lists

'<' not supported between instances of str and int


I'm trying to figure out the lowest score amongst a group of people.

My code:

list = [['Radhe',99],['Bajrangi',98],['Ram',95],['Shyam',94],['Bharat',89]]
min_score = list[0][1]
for x in list:
    for y in x:
        if (y < min_score):
            min_score=y
print(min_score)

What should I do different?


Solution

    1. list is a built-in-data type in python so you should rename the variable to something else such as l

    2. in your first for loop you are doing for x in list so you are assigning x to the first element of list which is ['Radhe', 99]. In your second for loop you are going through each item in x, the first of which is 'Radhe' and hence you are comparing an int to a string.

    Considering this, you can rewrite your code as:

    l = [['Radhe',99],['Bajrangi',98],['Ram',95],['Shyam',94],['Bharat',89]]
    min_score = l[0][1]
    for x in l:
        if (x[1] < min_score):
            min_score=x[1]
    print(min_score)
    

    which outputs:

    89
    

    alternatively you can use list comprehension to do it all in one line:

    min_score = min([x[1] for x in l])