Python – Find Longest String in a Set

To find the longest string in a Set in Python, you can use Python max() built-in function. max() built-in function takes the set of strings as first argument, key function of len() as second argument, and returns the longest string in the set.

The syntax of the function call to max(), to find the longest string in the set s is

max(s, key=len)
ADVERTISEMENT

Example

In the following program, we initialize a Python Set aSet with strings and find the longest of the strings (string with greatest length) in the set using max() function.

Program

# initialize set
aSet = {'apple', 'fig', 'banana'}

# find the longest string
longest = max(aSet, key=len)

print(f'longest string : {longest}')
Try Online

Output

longest string : banana

References

Conclusion

In this Python Tutorial, we learned how to find the longest string in a set, with the help of example programs.