Skip to content Skip to sidebar Skip to footer

Searching A List For The Longest String

I have a list which is generated when a user inputs a string: like this. It will take each individual word and append it to a list. I have a variable called max_l which finds the

Solution 1:

If you want to search a list for the longest string you could use the builtin max() function:

myList = ['string', 'cat', 'mouse', 'gradient']

printmax(myList, key=len)
'gradient'

max takes a 'key' argument to which you can assign a function(in this case len, another builtin function) which is applied to each item in myList.

In this case whichever len(string) for each string in myList returns the largest outcome(length) is your longest string, and is returned by max.

From the max docstring:

max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.

From the len docstring:

len(object) -> integerReturn the number of items of a sequence or mapping.

Generating list from user input:

In response to your comment, I thought I would add this. This is one way to do it:

user = raw_input("Enter a string: ").split() # with python3.x you'd be using input instead of raw_input

Enter a string: Hello there sir and madam # user enters this stringprint user
['Hello', 'there', 'sir', 'and', 'madam']

now to use max:

print max(user, key=len)
'Hello' # since 'Hello'and'madam'arebothof length 5, max just returns the firstone

Post a Comment for "Searching A List For The Longest String"