Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

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

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:

Code

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:

Code

Iowa
Pennsylvania

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

For example:

Code

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:

Code

4
12

Short and sweet.

Happy coding.