Their succinct syntax lets you create new lists in just one line of code. And this tutorial will teach you how you can do that. Over the next few minutes, you’ll learn:
How to create a new list using for loops,The syntax for using list comprehensions in Python, andHow to modify list comprehensions with if conditional statement.
In addition, you’ll also code several examples that will help you understand list comprehensions better. Let’s dive in.🌊
How to Create Python Lists Using for Loops
Suppose you have a list number of numbers nums. And you’d like to create another list that contains the cube of all the numbers in nums. Here’s how you’ll do it using a for loop in Python: In the above code, we have the following steps:
Initialize an empty list num_cubes.Loop through the nums list.Access each number num, and compute its cube using the exponentiation operator: num**3.Finally, append the cubed value to the list num_cubes
However, you can do this more easily using list comprehension in Python. Let’s proceed to learn its syntax.
Python List Comprehension Syntax
The general syntax for list comprehension is shown below. Let’s parse the above syntax.
In Python, lists are delimited by a pair of square brackets []—hence you need to enclose the list comprehension statement within [].
And this sounds simple, yes? Using this, we can simplify the syntax, as shown in the image below. Now that you’ve learned the syntax, it’s time to start coding. You can use Geekflare’s online Python IDE to follow along with these examples. Or you could run them on your local machine.
Python List Comprehension Examples
In the previous section, you created a new list num_cubes from nums. Let’s start by rewriting that using list comprehension.
Using List Comprehension with Numbers
Now let’s use the simplified syntax as follows:
Putting it all together, we have the following code snippet: Congratulations, you’ve coded your first list comprehension.🎉 Moving on, let’s work with Python strings.
Using List Comprehension with Strings
Suppose you have the list authors —you can rewrite the list below with your favorite authors.😄 Notice how the authors’ names are in lowercase in the above list. We would now like to format them in the title case and store them in a new list called author_list. So here’s all you need to do:
loop through the authors list and for each author in the list,call author.title() to get a title-cased copy of the string.
And the Python code for this is shown below: In the above output, observe how the names of all the authors have been formatted in the title case—which is what we wanted.
Using List Comprehension with Multiple Lists
So far, you’ve learned how to use list comprehension to create new lists from one existing list. Now let’s learn how to create a new list from multiple lists. For example, consider this problem: You have two lists l_arr and b_arr containing the lengths and breadths of 4 rectangles. And you need to create a new list area that includes the area of these 4 rectangles. Remember, area = length * breadth. You’ll need elements from both the lists (l_arr and b_arr) in order to calculate the area. And you can do it using Python’s zip() function. The following image describes this in detail. You have 4 values in l_arr and b_arr, so the range of indices is from 0 to 3. As you can see, the tuple 0 contains l_arr[0] and b_arr[0], tuple 1 contains l_arr[1] and b_arr[1], and so on. Therefore, you can loop through zip(l_arr,b_arr) as shown below: In the next section, you’ll learn how to use conditional statements inside a list comprehension.
Python List Comprehension with Condition Syntax
Let’s start by building on the previous syntax for list comprehension.
Here’s the syntax:
Instead of computing the
Python List Comprehension with Condition Examples
#1. You’re given the string “I’m learning Python in 2022”. You’d like to get a list of all digits in this string. So how do you do it? The code snippet below shows how you can collect the list of all digits in the string str1. In the above code:
you loop through the string str1,access each char to check if it’s a digit using the isdigit() method, andadd char to the new list digits only if it is a digit.
Let’s take another example. #2. You have a list of fruits.🍊 And you’d like to create a list starts_with_b that contains all fruits from the fruits list that start with b. You can use the startswith() method to write the condition. In the output above, we get ‘blueberry’ and ‘banana’ which are the two fruits that start with ‘b’ in the fruits list, as we expected. And that wraps up our discussion on list comprehension.
Conclusion
I hope this tutorial helped you understand list comprehensions in Python. Let’s summarize:
You can use [
Additionally, you’ve also coded several examples. As a next step, you can try rewriting some of your existing Python loops for list creation using list comprehension. Happy coding! Until the next tutorial.😄 You may now look at how to convert a list to a dictionary or learn how to handle files in Python.