The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

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

TODO: Pull subtitle into page object

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_start_default_section code_end_default_section

Short and sweet.

Happy coding.

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

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

-- p

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.

-- p

For example:

-- code/
-- python

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)

-- /code

-- p

Outputs:

-- code/

Iowa
Pennsylvania

-- /code

-- p

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

-- p

For example:

-- code/
-- python

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)

-- /code

-- p

Outputs:

-- code/

4
12

-- /code

-- p

Short and sweet.

-- p

Happy coding.


-- categories
-- Python

-- metadata
-- date: 2022-01-02 12:53:25
-- id: 239ustxm
-- status: published
-- type: post
-- SCRUBBED_NEO: false
-- site: aws