In python, why a variable which is assigned an integer value in a function but outside for loop ,return type as string

Here is the code, where I want to return the value in the dictionary with maximum length.
The code goes as follows:

def longest_value(d={}):
    max_len = 0
    for k,v in d.items():
        if len(v) > max_len:
            max_len = v

    return max_len

if __name__ == '__main__':
    fruits = {'fruit': 'apple', 'color': 'orange'}

When I run this code, the error thrown is:Type Error
however, if I check the type for max_len it returns string, even if I assign it as global still it throws the same error.
If I assign the variable inside the for loop it works, but I want to know why it is not working in the first case, what are the rules which needs to be followed here.

Though this question could be pretty lame, but I tried hard before posting, to search for an answer online, but I dint succeed. So appreciate any help on this.

>Solution :

The first iteration give you e.g.

k, v = 'fruit', 'apple'

and you set max_len = 'apple'. In the next iteration, you get

k, v = 'color', 'orange'

and you ask if len('orange') > 'apple'. The left side is an integer, the right one is a string.

If you set max_len = 0 inside the loop, you reset the counter each time (len(v) > 0), so the function always returns the last item.

Leave a Reply