Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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'}
    print(longest_value(fruits))

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.
Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading