Search code examples
pythonlistpython-2.7maxlength

Return len of the longest word in a list


Hi, I'm trying to make an python program that will return the length of the longest word in a list but it does not work so well for me.

here is the code:

def find_longest_word():
   list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
   max1 = ''
   for x in range (0, len(list1)):
      if (len(max1) < len(list1[x]) ):
          max1 = list1[x]
   return max1    


def main():
    m = find_longest_word()
    print len(m)

Solution

  • Actually, your problem is quite simple: you forgot to call the main function at the end of your script:

    main()
    

    When you do, it prints 8, just like it should.


    However, you can accomplish this task a lot easier if you use max and its key function:

    >>> list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
    >>> max(list1, key=len)
    'aaaaaaaa'
    >>> len(max(list1, key=len))
    8
    >>>
    

    Edit:

    While my above solution works fine, I want to offer an even shorter one I just thought of:

    >>> list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
    >>> max(map(len, list1))
    8
    >>>
    

    Instead of a key function, this solution uses map.