Victor
Victor

Reputation: 39

Find the index of the longest string and return that index

I can use this to figure out what the longest string in the sequence is but how exactly can I find the index of the longest string?

def longest_string(seq):
    max_list = max(seq,key=len)
    return max_list

print(longest_string(["h","el","lo","worl","d"]))

Output:

worl

Upvotes: 3

Views: 2206

Answers (2)

Vincent__A
Vincent__A

Reputation: 9

>>> seq = ["h","el","lo","worl","d"]
>>> seq.index(max(seq))
3

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174662

Instead of checking the length only, use the enumerate method to get the position as well:

>>> seq = ["h","el","lo","worl","d"]
>>> max(enumerate(seq), key=lambda x: len(x[1]))
(3, 'worl')

Then you can just return the first item of the tuple.

Upvotes: 5

Related Questions