Find The Longest And Shortest Strings And Lengths In A Python List

January - 2022

You can the shortest and longest items in a Python list of strings by using key=len with the built-in min() and max() functions.

For example:

state_names = ['Alabama', 'California', 'Iowa', 'Pennsylvania' ]

shortest_name = min(state_names, key=len)
longest_name = max(state_names, key=len)

print(shortest_name)
print(longest_name)

Outputs:

Iowa
Pennsylvania

A useful addition is to call len() on the results to find the lengths.

For example:

state_names = ['Alabama', 'California', 'Iowa', 'Pennsylvania' ]

shortest_string = len(min(state_names, key=len))
longest_string = len(max(state_names, key=len))

print(shortest_string)
print(longest_string)

Outputs:

4
12

Short and sweet.

Happy coding.