In Python, list comprehensions help you create new lists from existing iterables, like lists, strings, and tuples.
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
- The syntax for using list comprehensions in Python, and
- How to modify list comprehensions with
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:
nums = [2,3,5,7] num_cubes =  for num in nums: num_cubes.append(num**3) print(num_cubes) # Output [8, 27, 125, 343]
In the above code, we have the following steps:
- Initialize an empty list
- Loop through the
- Access each number
num, and compute its cube using the exponentiation operator:
- Finally, append the cubed value to the list
Note: In Python, the exponentiation operator
**is used with the syntax:
numis raised to the power
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.
<new_list> = [<expression> for <item> in <iterable>]
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
<iterable>signifies that you’re looping through an iterable. Any Python object that you can loop through and access individual items—such as lists, tuples, and strings are iterables.
<expression>is the output that you’d like to compute for every
And this sounds simple, yes?
In essence, you’d like to do something for all items in the list (or any iterable) to get a new list.
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
nums. Let’s start by rewriting that using list comprehension.
Using List Comprehension with Numbers
Now let’s use the simplified syntax as follows:
<do-this>: Here, you have to cube each
num. So replace
<all-items>: The looping variable is
num—the individual numbers in the list.
<this-list>: The existing list we have is
[num**3 for num in nums]is the final expression. ✅
Putting it all together, we have the following code snippet:
num_cubes = [num**3 for num in nums] print(num_cubes) # Output [8, 27, 125, 343]
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.😄
authors = ["jane austen","george orwell","james clear","cal newport"]
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
Note: In Python, the string method title() accepts a string as an argument, and returns a copy of the string formatted in the title case. That is, the first letter of each word is capitalized:
So here’s all you need to do:
- loop through the
authorslist and for each
authorin the list,
author.title()to get a title-cased copy of the string.
And the Python code for this is shown below:
authors = ["jane austen","george orwell","james clear","cal newport"] author_list = [author.title() for author in authors] print(author_list) # Output ['Jane Austen', 'George Orwell', 'James Clear', 'Cal Newport']
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
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.
l_arr = [4,5,1,3] b_arr = [2,1,7,9]
You’ll need elements from both the lists (
b_arr) in order to calculate the area. And you can do it using Python’s
Note: In Python, the
zip()function takes in one or more iterables as arguments with the syntax
zip(*iterables). It then returns an iterator of tuples, where the tuple
icontains the element
ifrom each of the iterables.
The following image describes this in detail. You have 4 values in
b_arr, so the range of indices is from 0 to 3. As you can see, the tuple
b_arr, and so on.
Therefore, you can loop through
zip(l_arr,b_arr) as shown below:
area = [l*b for l,b in zip(l_arr,b_arr)] print(area) # Output [8,5,7,27]
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:
<new_list> = [<expression> for <item> in <iterable> if <condition>]
Instead of computing the
<expression> for all items, you’d only like to do it for those items that satisfy a specific
condition := True. And this leads to a simplified syntax as shown:
▶ With that, let’s proceed to code examples.
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?
<char>.isdigit()acts on a character
Trueif it’s a digit (0-9); else it returns
The code snippet below shows how you can collect the list of all digits in the string
str1 = "I'm learning Python3 in 2022" digits = [char for char in str1 if char.isdigit()] print(digits) # Output ['3', '2', '0', '2', '2']
In the above code:
- you loop through the string
- access each
charto check if it’s a digit using the
charto the new list
digitsonly 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.
Trueif <str> starts with ‘char’; else it returns
fruits = ['blueberry','apple','banana','orange','cherry'] starts_with_b = [fruit for fruit in fruits if fruit.startswith('b')] print(starts_with_b) # Output ['blueberry', 'banana']
In the output above, we get
'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.
I hope this tutorial helped you understand list comprehensions in Python.
- You can use [<do this> for <all-items> in <this-list>] to create a new list using list comprehension.
- Additionally, you can use the syntax [<do this> for <all-items> in <this-list> if <condition-is-True>] with the
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.