Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Development USbreadcumb forward arrow iconList Comprehension in Python (With Examples)

List Comprehension in Python (With Examples)

Last updated:
22nd Aug, 2021
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
List Comprehension in Python (With Examples)

Python is among the world’s most popular programming languages. In 2020, it ranked second in RedMonk’s ranking of programming language popularity. The reason behind its widespread popularity is its easy-to-understand code and simplicity. Writing code in python is quite simple if you’re familiar with the syntax. One of its unique highlights is its list comprehension feature. You can perform Python comprehension for lists by writing just one line of code! 

The following points will illustrate what list comprehension is and how you can use it in different settings. We will also cover the differences present between list comprehension and for loops, which can be quite confusing. You’ll also learn about other related functions and how to use them: 

What is list comprehension Python?

Python offers multiple ways to create lists. One of the most effective ways among them is the list comprehension feature. It allows you to create lists by writing a single line of code. 

You can use list comprehensions to create new lists from other iterable elements such as arrays, strings, tuples, lists, etc. It is made up of brackets with the expression. The system executes the expression for every element with the for loop to iterate over every element. 

Ads of upGrad blog

The syntax for list comprehension in Python is as follows:

your_new_list = [expression for element in your_old_list if condition]

Here, your_new_list is the new list (or the result). The expression depends on the variable you used for every element in your_old_list. Finally, the “if condition” is the filter.

There are many reasons why Python developers prefer list comprehension over loops. The main reason is efficiency. You can create a list with far less effort and code when using list comprehension than you would while using loops

As it takes fewer lines of code than loops, list comprehension also saves you a lot of time. It keeps the code simple and makes it more user-friendly. Moreover, list comprehension covers an iterative statement into a formula. If you want to gain more expertise on python, check out our data science programs from top universities.

List comprehension Python examples

We are sharing several examples of how you can use list comprehension in Python. It would be best to study them and replicate them in your own program after you have understood how they work. It would help you understand properly how effective of a tool list comprehension truly is:

Example 1:

In this example, we’ll create a simple list by using Python comprehension:

Input:

a = [i for i in range(5)]

print a

Output:

[0, 1, 2, 3, 4]

Example 2:

In the example below, we’ll create a list with multiples of two:

Input:

new_list = [a*2 for a in range(10)]

Output

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Example 3

You can multiply every item in a list by using list comprehension:

Input

old_list = [1, 2, 3]

new_list = [item*2 for item in old_list]

print new_list

Output

[2, 4, 6]

Example 4

List comprehension isn’t limited to integers alone, you can also use it with strings. In this example, we’ll use list comprehension to create a list of the first letter of every word in our original list

Input

my_list = [“upgrad”, “is”, “fun”]

result = [word[0] for word in my_list]

print result

Output

[‘u’, ‘i’, ‘f’]

Example 5

You can also extract numbers from a string by using list comprehension

Input:

old_list = “upGrad 123 is fun”

new_list = [x for x in string if x.isdigit()]

print new_list

Output:

[‘1’, ‘2’, ‘3’]

Example 6: 

You can also use list comprehension with functions, which are a vital part of mathematical implementations of Python:

Input

# first, we’ll create a function called triple

def triple(x

return x*3

# now you have a working function that prints a result if you enter a valid value

>>> print triple(2)

Output:

6

Now you can use list comprehension with this function to create more lists

Input

>>> [triple(x) for x in range(5)]

print triple

Output

[0, 3, 6, 9, 12]

 

Difference between list comprehension and for loop

A common way to iterate through a list is by using the for loop. However, list comprehension is a more efficient method to iterate through a list as it lets you perform the task with fewer lines of code. 

Here’s an example to illustrate the difference. We’ll start with an empty list and modify it to make it a list of even numbers:

Input

# creating the empty list

old_list = []

# using the for loop to create the new list

for x in range(5):

old_list.append(x*2)

print old_list 

Output

[0, 2, 4, 6, 8]

As you can see, the for loop requires you to use the append function to create the new list. You also had to create an empty list first so you can use the loop to modify the same. However, with list comprehension, you wouldn’t have to use another function as you can complete the task with a single line of code:

Input

# creating the set by using list comprehension

old_list = [x*2 for x in range(5)]

print old_list

Output:

[0, 2, 4, 6, 8]

As list comprehension takes up less space and code, it also requires less computation power than using a for loop. This is beneficial while working on large programs as efficiency becomes a key issue when the code is substantially long.

However, when you’re using list comprehension, you should avoid using ones that are excessively long in one line. Otherwise, the code wouldn’t remain user-friendly and it can be quite challenging to share your work with other developers. Keep in mind that you rewrite every list comprehension into a for loop but you can’t rewrite every for loop into a list comprehension.

List comprehension is one of the many Python comprehension functionalities present in this programming language. Another comprehension functionality that’s highly popular is dictionary comprehension:

What is dictionary comprehension in Python?

Dictionary comprehension, as the name suggests, allows you to create dictionaries in Python. The syntax of a dictionary comprehension is:

{k:v for (k,v) in iterable}

Here, k stands for key and v stands for value.

Let’s see it at work. In the following example, we’ll create two lists and use dictionary comprehension to generate a dictionary from them:

Input:

# using Python to showcase dictionary comprehension

# creating two lists to represent keys and values

keys = [1, 2, 3, 4, 5]

values = [‘a’, ‘b’, ‘c’ ‘d’, ‘e’]

# implementing dictionary comprehension

new_dict = { k:v for (k,v) in zip(keys, values)}

print new_dict

Output:

{1 : ‘a’, 2 : ‘b’, 3 : ‘c’, 4 : ‘d’. 5 : ‘e’}

Dictionary comprehension makes it quite easy to create dictionaries in Python. However, you can also use list comprehension to generate a dictionary. In the following example, we’ll use list comprehension and create a dictionary:

Input:

new_dict = {x: x*2 for x in [5, 4, 3, 2, 1]}

print new_dict

Output:

{5 : 10, 4 : 8, 3 : 6, 2 : 4, 1 : 2}

Become a Python Expert

List comprehension is one of the many functionalities present in Python. It is a highly versatile and useful programming language. Moreover, the syntax of Python is also very easy to understand and takes quite a little effort to get used to. Apart from these benefits, Python also offers numerous libraries to its users.

It has a thriving community of developers and programmers who add new libraries to its collection regularly. The numerous libraries and functions available for Python make it useful in different sectors such as software development, data science, machine learning, and others.

If you’re interested in learning Python, you should learn it in the context of the field you want to enter. Also, recruiters always look for certified professionals in this field because it assures them of the candidate’s expertise.

Due to these reasons, it would be best to join a python course if you’re interested in pursuing a career with this skill. The International Institute of Information Technology Bangalore offers an Executive PG Program in Software Development with upGrad which is perfect for those who want to become experts in this programming language and pursue a tech career. The course will give you a well-structured way to study Python and other trending technologies to help you enter the industry as a job-ready professional.

upGrad has over 40,000 paid learners in 85+ countries. Joining this program will also allow you to network internationally through upGrad’s vast learner base. The Executive PG Program in Software Development course is an online program that lasts for 13 months. It only requires a time commitment of 15 hours a week.

The program offers six specializations to choose from

  • Cybersecurity
  • DevOps
  • Cloud computing
  • Big data
  • Blockchain development
  • Full-stack development 

Along with these advantages, upGrad also offers 360-degree career assistance with this program so you can kickstart your career easily. You can learn more about the course here: Executive PG Program in Software Development.

Conclusion

Ads of upGrad blog

You can try out list comprehension with simple lists at first and then move onto more complex applications of this functionality. List comprehension is an example of how flexible and robust Python programming is. 

What do you think of list comprehension? How would you use it in your program?

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.
Get Free Consultation

Selectcaret down icon
Select Area of interestcaret down icon
Select Work Experiencecaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Software Development Course

Frequently Asked Questions (FAQs)

1 What does list comprehension in Python do?

List comprehension Python allows you to create lists efficiently and by only using a single line of code. It’s one of the most robust functionalities in Python.

2 What is dictionary comprehension?

Dictionary comprehension allows you to create dictionaries for two lists. It uses keys and values to create the required dictionary.

3 Is list comprehension better than for loop?

Yes, in most cases, list comprehension is a much better way to create lists. It requires less code, time, and computing power than for loops to generate lists.

Explore Free Courses

Suggested Blogs

Top 19 Java 8 Interview Questions (2023)
6085
Java 8: What Is It? Let’s conduct a quick refresher and define what Java 8 is before we go into the questions. To increase the efficiency with
Read More

by Pavan Vadapalli

27 Feb 2024

Top 10 DJango Project Ideas & Topics
12775
What is the Django Project? Django is a popular Python-based, free, and open-source web framework. It follows an MTV (model–template–views) pattern i
Read More

by Pavan Vadapalli

29 Nov 2023

Most Asked AWS Interview Questions & Answers [For Freshers & Experienced]
5676
The fast-moving world laced with technology has created a convenient environment for companies to provide better services to their clients. Cloud comp
Read More

by upGrad

07 Sep 2023

22 Must-Know Agile Methodology Interview Questions & Answers in US [2024]
5397
Agile methodology interview questions can sometimes be challenging to solve. Studying and preparing well is the most vital factor to ace an interview
Read More

by Pavan Vadapalli

13 Apr 2023

12 Interesting Computer Science Project Ideas & Topics For Beginners [US 2023]
11004
Computer science is an ever-evolving field with various topics and project ideas for computer science. It can be quite overwhelming, especially for be
Read More

by Pavan Vadapalli

23 Mar 2023

Begin your Crypto Currency Journey from the Scratch
5460
Cryptocurrency is the emerging form of virtual currency, which is undoubtedly also the talk of the hour, perceiving the massive amount of attention it
Read More

by Pavan Vadapalli

23 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5560
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5042
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Top 10 Cyber Security Books to Read to Improve Your Skills
5534
The field of cyber security is evolving at a rapid pace, giving birth to exceptional opportunities across the field. While this has its perks, on the
Read More

by Keerthi Shivakumar

21 Mar 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon