In this tutorial, we will learn how to find the length of each string in a list in Python. This can be particularly useful when you’re working with data preprocessing and need to manipulate lists containing strings of different lengths. We will use two different approaches to achieve this: using list comprehensions and using the built-in map()
function.
Step 1: Creating a sample list of strings
First, let us create a sample list of strings for this example. The list will contain a few simple words:
1 |
string_list = ['apple', 'banana', 'cherry', 'date', 'fig'] |
Step 2: Using list comprehensions to find the length of strings in the list
List comprehensions are a powerful and concise way of constructing lists in Python. In this step, we will use them to create a new list containing the length of each string in our original list.
Here’s the list comprehension to achieve that:
1 2 |
lengths_list = [len(s) for s in string_list] print(lengths_list) |
This code will output the following list, displaying the length of each string in the original list:
[5, 6, 6, 4, 3]
Step 3: Using the map() function to find the length of strings in the list
Another way to find the length of each string in the list is to use the built-in map()
function. The map()
function applies a given function to all items of an iterable and returns an iterator. Since we need a list as the output rather than an iterator, we will wrap the map()
function with the list()
function
Here’s the code using map()
to find the length of each string in our list:
1 2 |
lengths_list_map = list(map(len, string_list)) print(lengths_list_map) |
This code will also output the same list of lengths as the list comprehension method:
[5, 6, 6, 4, 3]
Full code
Here’s the complete code, including both ways of finding the length of strings in a list in Python:
1 2 3 4 5 6 7 8 9 |
string_list = ['apple', 'banana', 'cherry', 'date', 'fig'] # Using list comprehension lengths_list = [len(s) for s in string_list] print(lengths_list) # Using map() function lengths_list_map = list(map(len, string_list)) print(lengths_list_map) |
Both methods will give the following output:
[5, 6, 6, 4, 3] [5, 6, 6, 4, 3]
Conclusion
We’ve covered how to find the length of each string in a list using both list comprehensions and the map()
function. The choice between these methods depends on your coding style and preferences. Both methods are efficient and will help you when working with lists of strings in Python.