'Nonetype has no len()

d=("adf": 1, "bdc":2,"cdsd":4)

def longest_key (d):

longest None

for key in d: if not longest or len (key) > len (longest):

longest = key

return longest

print(longest_key(d)).

When i do this the program is fine and no error occurs but

d=("adf": 1, "bdc":2,"cdsd":4) def longest_key (d):

longest = None

for key in d: if len (key) > len (longest):

longest key

return longest print (longest_key(d)).

When i do this it shows type error object of type Nonetype has no len()



Solution 1:[1]

You set longest to None and you're trying to get its length. In the second function, it errors because you don't have the if not longest condition. The first function works because short circuit evaluation means that len(longest) will not be evaluated.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler Liu