Find Index of Shortest & Longest String in List in Python (Example)

 

Hi! This tutorial will show you how to get the index of the shortest and longest strings in list in the Python programming language.

Here is an overview:

Let’s dive into the Python code!

 

Create Sample List of Strings

Here, we will create the sample Python list of strings that we will use in the example in this tutorial. So, in your preferred Python coding IDE, run the line of code below to create the sample list of strings:

my_list = ["chair", "wardrobe", "stool", "bed"]
 
print(my_list)
 
# ['chair', 'wardrobe', 'stool', 'bed']
 
print(type(my_list))
 
# <class 'list'>

With the sample list of strings created, let us now see how to determine the index of the shortest and longest strings in the list.
 

Example: Get Index of Shortest & Longest String Using For Loop, min(), max() & enumerate()

In this example, we will demonstrate how to use a for loop, the min() function, the max() function, and the enumerate() function to return the index of the shortest and longest strings in the list. Run the script below:

# get length of each string in list
length = []
for i in range(len(my_list)):
  length.append(len(my_list[i]))
 
 
# get index of shortest string
for i,j in enumerate(length):
  if j == min(length):
    print(f"The index of the shortest string is {i}")
 
 
# get index of longest string
for i,j in enumerate(length):
  if j == max(length):
    print(f"The index of the longest string is {i}")
 
 
# The index of the shortest string is 3
# The index of the longest string is 1

What we did in the above example is very simple. First, we determined the length of individual strings in the list, by running a loop through the list, and parsing that to the len() function, which then returned a list containing the length of each string in the list.

Next, to get the length of the shortest and longest string, we ran for loops through the output of enumerate(length), which is a list of tuples containing the values and their respective index positions. We then used a conditional statement to return the index number (i) when the value (j) is equal to the min(length) for shortest string, and max(length) for longest string.

 

Define a Function for Easy Code Reusability

For easy reusability of the code on other string lists, it is best to define a function that is called only when it is needed, instead of having to rewrite the code each time, which is rather tedious. In the script below, we will define a function that will run our code above whenever the function is called:

def getIndex(data):
 
    length = []
    for i in range(len(data)):
      length.append(len(data[i]))
 
    for i,j in enumerate(length):
      if j == min(length):
        print(f"The index of the shortest string is {i}")
 
    for i,j in enumerate(length):
      if j == max(length):
        print(f"The index of the longest string is {i}")

The script is basically the same. The only differences you would notice are the def keyword, which stands for “define”, and the function name getIndex() wherein we specified a parameter, or argument, data. With this, if a new string list is parsed to this function, it takes the place of the argument “data” anywhere it appears in the code.

Let us try out our new function on another string list:

new_list = ["aeroplane","ship", "bus", "train"]
 
getIndex(data = new_list)
 
# The index of the shortest string is 2
# The index of the longest string is 0

With that, we have demonstrated how to find the shortest and longest string index in a list in Python. I do hope you found this tutorial helpful!
 

Video, Further Resources & Summary

Do you need more explanations on how to find the index of the shortest and longest string in a list in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain in some more detail how to find the index of the shortest and longest string in a list in Python.

 

The YouTube video will be added soon.

 

Furthermore, I encourage you to check out other interesting Python list tutorials on Statistics Globe, starting with these:

This post has shown how to find the index of the shortest and longest string in a list in Python. In case you have further questions, you may leave a comment below.

 

R & Python Expert Ifeanyi Idiaye

This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top