TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python List Comprehension
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python List Comprehension

Last updated: Apr 23, 2024 10:53 pm
By Meenakshi Agarwal
Share
16 Min Read
Master Python List Comprehension in 2 Minutes
Master Python List Comprehension in 2 Minutes
SHARE

This tutorial explains Python List Comprehension, the fastest way to create, iterate, and return new lists with elements filtered using conditions made of a boolean expression or if-else.

Contents
What is List Comprehension in Python?Basic Python List ComprehensionAdvanced Python List Comprehension IfPython List Comprehension If ElseList Comprehension ExamplesExample-1Example-2Example-4Example-5When should you not use the LC?Self-Assessment Test

How to Use List Comprehension in Python

You may find it similar to the Python filter() method that filters values based on some condition. However, list comprehension has a much more powerful syntax which gives options to add expressions and use if statements.

First, let’s answer this question: Why use List Comprehension?

The main reason is that it makes you write less code. It prevents you from using a for loop to go through the list.

That’s correct, but there are more benefits. For instance, it’s faster because it optimizes operations that happen right within the List Comprehension itself.

This inlining of operations reduces function call overhead. And as you use it, you might discover even more advantages. It is a unique one-liner coding technique in Python. Let’s dig into it quickly.

Please go through each section so that you can understand it in depth. And it shouldn’t take more than two minutes to read. Also, there is a short quiz/exercise given at the end of the tutorial.

What is List Comprehension in Python?

Python List Comprehension is an inline way of writing logic to search the existing list, do some operations on it, and return a new list.

You can achieve the same effect by using a for loop or the filter function. But it is only list comprehension which can do it with one line of code.

Basic Python List Comprehension

Look at its signatures below:

# Basic Syntax - Python List Comprehension 
[new_list] = [expr1 FOR element IN in_list]

It is the most basic form of list comprehension in Python. The ideal use case to apply it is when you want to perform some operations on list elements.

See this example where we are converting each element of a list to upper case using list comprehension.

# Using Python List Comprehension
langs = ['python', 'csharp', 'go', 'javascript', 'php', 'mysql']
langs = [item.upper() for item in langs]
print(langs)

The output is:

['PYTHON', 'CSHARP', 'GO', 'JAVASCRIPT', 'PHP', 'MYSQL']

Advanced Python List Comprehension If

# Advanced Syntax - Python List Comprehension If
out = [expr1 for element in in_list if <condition> OR/AND expr2]

Note:

With this format, you can add an if condition with Python list comprehension and join it with OR and AND clauses.

The FOR (for), IN (in), IF (if), and OR/AND (or/and) are reserved keywords in Python. Rest others like new_list, expr1, element, condition, in_list, and expr2 are either variable names or expressions.

The syntax itself is quite explanatory. It saves you from writing multiple lines of code (such as a loop requires) and improves readability.

Let’s take an example where we have a list of fruits. We have to form a new list that contains only fruit names starting with a vowel.

# Using Python List Comprehension If condition
# Find fruits starting with a vowel
fruits = ['Apples', 'Oranges', 'Guavas', 'Grapes', 'Mangoes', 'Apricots', 'Olives']
fruits = [fruit for fruit in fruits if fruit[0].lower() in ['a', 'e', 'i', 'o', 'u']]
print(fruits)

The result is:

['Apples', 'Oranges', 'Apricots', 'Olives']

Since list comprehension is related to the list data structure, you must also know about them. Check out the below tutorial.

Python List Comprehension If Else

To use if else with Python list comprehension, the following is the syntax, you can try:

# Advanced Syntax - Python List Comprehension If Else
out = [expression_if_true if condition else expression_if_false for item in iterable]

As an illustration, assume we have a list of integers and strings. With the help of Python list comprehension if else, for each value in the list, do the following:

  • If the value is an integer, return it as is.
  • If it is a string, return -1.

Here is the code to achieve this by using the list comprehension if else:

my_list = [1, 2, "python", 3, 4, 5, "comprehension"]

print([x if isinstance(x, int) else -1 for x in my_list])

# [1, 2, -1, 3, 4, 5, -1]

Also Check: List in Python with Examples

Let’s now see some practical things with the help of examples.

List Comprehension Examples

While using Python list comprehension, you should be wise enough to use it. In some cases, it is better to write more code to maintain readability.

Let’s assume that you have a list of 1000 integers which has both odd and even numbers. Below is the test input list.

# list of integers for the test
list_of_ints = range(1, 1000)

We used the Python range() function to generate 1K numbers.

You’ll now have multiple tasks at hand. And you should be using the list comprehension technique.

Example-1

Your first task is to create a list of even integers using the list comprehension method.

Find even numbers using list comprehension
"""
 Desc: Program to filter even numbers from a list of 1000 integers
 Method: By using Python list comprehension
"""

# list of 1000 integers for the test
list_of_ints = range(1, 1000)

def test_ListComprehension():
   # let's prepare the list comprehension
   list_of_even_nums = [x for x in list_of_ints if x%2 == 0]
   return list_of_even_nums

if __name__ == '__main__':

   out = test_ListComprehension()
   # print list of even numbers and its size
   print("Found {} even numbers: {}".format(len(out), out))

Below is the output captured after the execution of the above code. We used the Python string format() function to print the output dynamically.

Found 499 even numbers: [2, 4, 6, 8, 10, ..., 998]

Note: We didn’t show the full output as it was a lot to display 499 odd numbers.

Example-2

Your second assignment is to compute the performance of list comprehension vs. for loop. So, you’ll be writing two functions and using the Python time module to measure their execution time.

Python List comprehension vs. for loop
"""
 Desc: Program to measure performance of list comprehension vs. for loop
 Method: Using list comprehension and for loop
"""
import time as t

# list of 1000 integers for the test
list_of_ints = range(1, 1000)

def test_ListComprehension():
   # let's prepare the list comprehension
   list_of_even_nums = [x for x in list_of_ints if x%2 == 0]
   return list_of_even_nums

def test_ForLoop():
   # using for loop to find out even numbers
   even_nums = []
   for item in list_of_ints:
      if item%2 == 0:
         even_nums.append(item)
   return even_nums

if __name__ == '__main__':

   # measure performance of list comprehension
   start = t.time()
   out = test_ListComprehension()
   end = t.time()
   # print list of even numbers and its size
   print("Found {} even numbers in {}s: {}".format(len(out), round(end - start, 6), out))

   # measure performance of for loop
   start = t.time()
   out = test_ForLoop()
   end = t.time()
   # print list of even numbers and its size
   print("Found {} even numbers in {}s: {}".format(len(out), round(end - start, 6), out))

Since we have to measure the performance of the two functions, let’s run the program several times.

The first iteration result is:

Found 499 even numbers in 0.000176s: [2, 4, 6, 8, 10, ..., 998]
Found 499 even numbers in 0.000291s: [2, 4, 6, 8, 10, ..., 998]

The second iteration result is:

Found 499 even numbers in 0.000208s: [2, 4, 6, 8, 10, ..., 998]
Found 499 even numbers in 0.000291s: [2, 4, 6, 8, 10, ..., 998]

And finally, the third iteration result is as follows:

Found 499 even numbers in 0.00021s: [2, 4, 6, 8, 10, ..., 998]
Found 499 even numbers in 0.000279s: [2, 4, 6, 8, 10, ..., 998]

It is quite evident from the results that List Comprehension was quite faster than the for loop in creating a new list of integers.

In the next task or example, we’ll see the next level of Python List Comprehension.

Also Read: Python for loop

Example-4

Make a single list comprehension to return two lists, one for even and another for odd numbers.

Single LC Expression to return two lists

Yes. Don’t worry. It is 100% doable, and let’s see how to achieve it.

"""
 Desc: Program to find odd and even numbers from a list of integers
 Method: By using a single Python list comprehension
"""
# list of 1000 integers for the test
list_of_ints = range(1, 1000)

oddNums = []
evenNums = []

def test_ListComprehension():
   # let's prepare the list comprehension
   return [x for x in list_of_ints if x%2 == 0 or oddNums.append(x)]

if __name__ == '__main__':

   evenNums = test_ListComprehension()
   # print list of even numbers and its size
   print("Found {} even numbers: {}".format(len(evenNums), evenNums))
   # print list of odd numbers and its size
   print("Found {} odd numbers: {}".format(len(oddNums), oddNums))

Here is the outcome of the above program:

Found 499 even numbers: [2, 4, 6, 8, 10,..., 998]
Found 500 odd numbers: [1, 3, 5, 7, 9, 11, ..., 999]

We haven’t finished yet. You need to go over one more task to get through.

Example-5

Here, you need to find even numbers from a list of lists of integers. We are giving a clue which is to use nested list comprehension.

python nested list comprehension

It is not at all tough to create a nested comprehension. First, write a regular LC and then wrap it with an outer LC.

"""
 Desc: Program to find even numbers from a list of list of integers
 Method: By using nested Python list comprehension
"""
# list of lists of integers for the test
list_of_ints = [[1, 2, 3, 4], [2, 5, 6], [7, 8, 9, 10]]

def nested_ListComprehension():
   # let's prepare the nested list comprehension
   return [[x for x in inner_list if x%2 == 0] for inner_list in list_of_ints]

if __name__ == '__main__':

   evenNums = nested_ListComprehension()
   # print list of even numbers and its size
   print("Found {} list of even numbers: {}".format(len(evenNums), evenNums))

The output is:

Found 3 list of even numbers: [[2, 4], [2, 6], [8, 10]]

Lastly, it is essential to discuss when not to use the Python list comprehension.

When should you not use the LC?

The list comprehension works like magic once you get used to it. However, there are scenarios where using it doesn’t make sense.

One such use case is when you have more than one condition to operate. The readability would go down as the number of if…else grows.

lucky_number = [x for x in range(1, 1000) if x%2 != 0 and x > 99 and x not in range(500, 1000)]

Another point is when you need to raise some exception or add a Python try-except block. For example, the Python list comprehension won’t work in the below case.

alphabets = ['P', 'Y', 'T', 'H', 'O', 'N', 3, 6]
print(alphabets)

lower_case = [x.lower() for x in alphabets]
print(lower_case)

The code is valid, but when you run it, it fails with AttributeError. You can’t change the case of a number. So, rather handle it via for loop.

alphabets = ['P', 'Y', 'T', 'H', 'O', 'N', 3, 6]
print("Pre:- ", alphabets)

lower_case = []
for alphabet in alphabets:
  try:
    out = alphabet.lower()
    lower_case.append(out)
  except AttributeError:
    lower_case.append(alphabet)

print("Post:- ", lower_case)

Here is the result:

Pre:- ['P', 'Y', 'T', 'H', 'O', 'N', 3, 6]
Post:- ['p', 'y', 't', 'h', 'o', 'n', 3, 6]

Self-Assessment Test

Now, face this quick Python list comprehension quiz. It’ll help you remember the important points you learned from this tutorial.

1. What is the result of the code shown below?

import math
[str(round(math.e)) for i in range (1, 5)]

A. [‘3’, ‘3’, ‘3’, ‘3’, ‘3’, ‘3’]
B. [‘2.7’, ‘2.71’, ‘2.718’, ‘2.7182’, ‘2.71828’, ‘2.718281’]
C. [‘3’, ‘3’, ‘3’, ‘3’, ‘3’]
D. [‘2.7’, ‘2.71’, ‘2.718’, ‘2.7182’, ‘2.71828’]
E. [‘2’, ‘2’, ‘2’, ‘2’, ‘2’]

Hover here to view the answer.
Answer. C

2. What is the result of this list comprehension expression?

val=[11.0]
[round((i-11)*3/6) for i in val]

A. [0]
B. 0
C. [0.0]
D. Error

Hover here to view the answer.
Answer. A

3. What is the result of the code given below?

print([char.upper() for char in "python"])

A. [‘PYTHON’].
B. ‘PYTHON’
C. [‘P’, ‘Y’, ‘T’, H’, ‘O’, ‘N’].
D. PYTHON

Hover here to view the answer.
Answer. C

4. What is the result of this simple Python list comprehension?

langs = ['Python', 'Csharp', 'JavaScript']
langs_i = [lang.lower() for lang in langs]
print(langs_i[2][0])

A. None
B. p
C. c
D. j

Hover here to view the answer.
Answer. D

5. What is the result of the code given below?

vec = [[11, 21, 31],
[42, 52, 62],
[73, 83, 93]]
[vec[i][len(vec)-1-i] for i in range(len(vec))]

A. [11, 52, 93]
B. [31, 52, 73]
C. [42, 52, 62]
D. [21, 52, 83]

Hover here to view the answer.
Answer. B

We hope that after wrapping up this tutorial, you are now comfortable with Python list comprehension. However, you may practice more with the given examples and gain more confidence.

Learn Python Step-by-Step

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python multiline string simplified with examples How to Use Multiline Strings in Python
Next Article Python Heapq with Examples Understanding Python Heapq and Its Functions

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x