Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

List Comprehension in Python (With Examples)

Updated on 26 September, 2022

6.8K+ views
8 min read

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.

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

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?

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.

RELATED PROGRAMS