Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python List Comprehension

Python List Comprehension - Complete Guide

Learn how to create lists concisely and efficiently using Python list comprehension.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Introduction to List Comprehension
  • Basic Syntax
  • With Conditional Filtering
  • Using if-else in Comprehension
  • Nested List Comprehension
  • Multiple Conditions
  • Performance Considerations
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • Basic syntax — how list comprehension works
  • Conditional filtering — using if to filter elements
  • if-else in comprehension — conditional expressions
  • Nested comprehension — working with nested loops
  • Multiple conditions — combining filters
  • Performance — when and why to use comprehension
  • Common mistakes — and how to avoid them

Introduction to List Comprehension

List comprehension is a concise and powerful Python feature that allows you to create new lists by applying an expression to each element of an existing iterable. It combines the process of iteration and transformation into a single, readable line of code.

List comprehensions are often more readable and performant than traditional for loops for list creation. They follow a natural syntax that closely resembles how you would describe the operation in plain English.

The basic structure of a list comprehension is:

new_list = [expression for item in iterable if condition]

Where:

  • expression — the operation to perform on each element
  • item — the variable representing each element
  • iterable — the source collection (list, range, etc.)
  • if condition — optional filter (only include items that satisfy the condition)

💡 Key concept: List comprehension is a syntactic sugar for a for loop with an append operation. It is not always the best choice — use it for simple transformations and filters, but avoid it when readability would suffer.

Basic Syntax

1

Transforming Elements

The simplest form of list comprehension applies an expression to each element in the iterable and creates a new list with the results.

# Basic list comprehension
numbers = [1, 2, 3, 4, 5]

# Square each number
squares = [num ** 2 for num in numbers]
print(squares)  # [1, 4, 9, 16, 25]

# Convert to strings
str_numbers = [str(num) for num in numbers]
print(str_numbers)  # ['1', '2', '3', '4', '5']

# Apply a function
def double(x):
    return x * 2

doubled = [double(num) for num in numbers]
print(doubled)  # [2, 4, 6, 8, 10]

# Working with strings
words = ["apple", "banana", "cherry"]
uppercase = [word.upper() for word in words]
print(uppercase)  # ['APPLE', 'BANANA', 'CHERRY']

# Get lengths
lengths = [len(word) for word in words]
print(lengths)  # [5, 6, 6]

Characteristics:

  • Creates a new list — original list remains unchanged
  • Syntax: [expression for item in iterable]
  • Can use any expression including function calls
  • Works with any iterable (lists, tuples, ranges, etc.)
  • Often faster than equivalent for loop

Quick Check: Does list comprehension modify the original list? (Answer: No, it creates a new list)

With Conditional Filtering

2

Filtering Elements with if

The if clause in a list comprehension allows you to filter elements — only items that satisfy the condition are included in the new list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Only even numbers
evens = [num for num in numbers if num % 2 == 0]
print(evens)  # [2, 4, 6, 8, 10]

# Only numbers greater than 5
greater_than_5 = [num for num in numbers if num > 5]
print(greater_than_5)  # [6, 7, 8, 9, 10]

# With strings - words with length > 5
words = ["apple", "banana", "cherry", "date", "elderberry"]
long_words = [word for word in words if len(word) > 5]
print(long_words)  # ['banana', 'cherry', 'elderberry']

# Words starting with a specific letter
a_words = [word for word in words if word.startswith('a')]
print(a_words)  # ['apple']

# Filtering and transforming together
squares_of_evens = [num ** 2 for num in numbers if num % 2 == 0]
print(squares_of_evens)  # [4, 16, 36, 64, 100]

Characteristics:

  • Syntax: [expression for item in iterable if condition]
  • Only items that satisfy the condition are included
  • Can be combined with transformation in the same line
  • Equivalent to: for item in iterable: if condition: append(expression)

Quick Check: What does the if clause do in list comprehension? (Answer: It filters elements — only those that satisfy the condition are included)

Using if-else in Comprehension

3

Conditional Expressions

The if-else construct can be used within the expression part of a list comprehension to apply different transformations based on a condition.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Replace even numbers with "even", odd with "odd"
labels = ["even" if num % 2 == 0 else "odd" for num in numbers]
print(labels)  # ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']

# Mark numbers greater than 5 as "high", others as "low"
categories = ["high" if num > 5 else "low" for num in numbers]
print(categories)  # ['low', 'low', 'low', 'low', 'low', 'high', 'high', 'high', 'high', 'high']

# Square even numbers, leave odd numbers unchanged
processed = [num ** 2 if num % 2 == 0 else num for num in numbers]
print(processed)  # [1, 4, 3, 16, 5, 36, 7, 64, 9, 100]

# With strings - convert to uppercase if length > 3, else lowercase
words = ["apple", "banana", "cat", "dog", "elderberry"]
modified = [word.upper() if len(word) > 3 else word.lower() for word in words]
print(modified)  # ['APPLE', 'BANANA', 'cat', 'dog', 'ELDERBERRY']

Important distinction:

  • if at the end — filters items: [x for x in list if condition]
  • if-else in expression — transforms items: [x if condition else y for x in list]
  • Both can be used in the same comprehension
# Filter AND transform
result = [num ** 2 if num % 2 == 0 else num for num in numbers if num > 3]
# First filter: num > 3, then transform: square if even, keep if odd

Quick Check: What is the difference between if at the end and if-else in expression? (Answer: if at the end filters; if-else in expression transforms)

Nested List Comprehension

4

Working with Nested Loops

List comprehension can include nested loops, similar to nested for loops. This is useful for flattening lists or working with matrices.

# Flatten a matrix (list of lists)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Equivalent nested for loop:
# flattened = []
# for row in matrix:
#     for num in row:
#         flattened.append(num)

# Nested comprehension with filtering
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
even_numbers = [num for row in matrix for num in row if num % 2 == 0]
print(even_numbers)  # [2, 4, 6, 8]

# Creating a multiplication table
table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
print(table)
# [[1, 2, 3, 4, 5],
#  [2, 4, 6, 8, 10],
#  [3, 6, 9, 12, 15],
#  [4, 8, 12, 16, 20],
#  [5, 10, 15, 20, 25]]

# Transpose a matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(3)]
print(transposed)  # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Characteristics:

  • Loop order follows the same order as nested for loops
  • Can have multiple levels of nesting
  • Useful for flattening and matrix operations
  • Readability decreases with too many nested levels

Quick Check: What is the order of loops in a nested list comprehension? (Answer: The order matches nested for loops — outer loop first, then inner loop)

Multiple Conditions

5

Combining Filters

List comprehension supports multiple conditions using multiple if clauses or logical operators.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Multiple if conditions
result = [num for num in numbers if num > 3 if num < 8]
print(result)  # [4, 5, 6, 7]

# Using logical operators (and, or)
result = [num for num in numbers if num > 3 and num < 8]
print(result)  # [4, 5, 6, 7]

# Numbers that are even OR greater than 7
result = [num for num in numbers if num % 2 == 0 or num > 7]
print(result)  # [2, 4, 6, 8, 9, 10]

# With strings - words with length > 3 AND contain 'a'
words = ["apple", "banana", "cat", "dog", "grape", "kiwi"]
result = [word for word in words if len(word) > 3 and 'a' in word]
print(result)  # ['apple', 'banana', 'grape']

Guidelines:

  • Multiple if clauses act as AND conditions
  • Use and, or for more complex logic
  • Multiple if clauses are less common than using and/or
  • Keep conditions simple for readability

Performance Considerations

6

When to Use List Comprehension

List comprehension is generally faster than a for loop because it is implemented in C and optimized for list creation. However, readability should be the primary consideration.

import time

# Using for loop
numbers = range(1, 1000000)
start = time.time()
squares_loop = []
for num in numbers:
    squares_loop.append(num ** 2)
print(f"Loop time: {time.time() - start:.4f}s")

# Using list comprehension
numbers = range(1, 1000000)
start = time.time()
squares_comp = [num ** 2 for num in numbers]
print(f"Comprehension time: {time.time() - start:.4f}s")

# Output (approximate):
# Loop time: 0.1234s
# Comprehension time: 0.0789s

# When NOT to use list comprehension:
# 1. Complex logic
# 2. Side effects (e.g., printing)
# 3. Multiple operations
# 4. Very large datasets (memory considerations)

Performance summary:

  • Faster: List comprehension is usually faster than for loops
  • Memory: Creates a complete list in memory
  • Use when: Simple transformation or filtering
  • Avoid when: Complex logic, side effects, or very large datasets
  • For very large data: Consider generator expressions: (x ** 2 for x in numbers)

Quick Check: Is list comprehension always the best choice? (Answer: No — avoid it for complex logic, side effects, or very large datasets)

Common Mistakes

7

Pitfalls and Solutions

Confusing Filter and Transformation

# Incorrect — trying to use if-else as a filter
numbers = [1, 2, 3, 4, 5]
# This will raise an error because if-else must be in the expression
# result = [num if num % 2 == 0 for num in numbers]  # SyntaxError

# Correct — if-else in expression, if at end for filtering
result = [num for num in numbers if num % 2 == 0]  # Filter
result = ["even" if num % 2 == 0 else "odd" for num in numbers]  # Transform

Variable Shadowing

# Incorrect — overwrites existing variable
numbers = [1, 2, 3, 4, 5]
num = 10  # Original variable
squares = [num ** 2 for num in numbers]  # num is overwritten
print(num)  # 5 (not 10!)

# Correct — use different variable names in comprehension
squares = [n ** 2 for n in numbers]

Overly Complex Comprehensions

# Bad — too complex, hard to read
result = [x ** 2 if x % 2 == 0 else x ** 3 if x % 3 == 0 else x for x in range(1, 20)]

# Better — use a regular loop for complex logic
result = []
for x in range(1, 20):
    if x % 2 == 0:
        result.append(x ** 2)
    elif x % 3 == 0:
        result.append(x ** 3)
    else:
        result.append(x)

Using Comprehension for Side Effects

# Incorrect — using comprehension for side effects
numbers = [1, 2, 3, 4, 5]
# Don't do this: [print(num) for num in numbers]  # Prints but creates an unnecessary list

# Correct — use a for loop for side effects
for num in numbers:
    print(num)

Quick Check: When should you NOT use list comprehension? (Answer: When the logic is complex, for side effects, or when readability suffers)

Interactive Editor

Experiment with list comprehension in the interactive editor below. Modify the code and observe the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
LIST COMPREHENSION PRACTICE
========================================

Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Words: ['apple', 'banana', 'cherry', 'date', 'elderberry']

1. BASIC TRANSFORMATION
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

2. FILTERING
Even numbers: [2, 4, 6, 8, 10]

3. IF-ELSE IN EXPRESSION
Labels: ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']

4. NESTED COMPREHENSION
Flattened matrix: [1, 2, 3, 4, 5, 6, 7, 8, 9]

5. WORKING WITH STRINGS
Long words uppercase: ['BANANA', 'CHERRY', 'ELDERBERRY']

6. MULTIPLE CONDITIONS
Numbers between 3 and 8: [4, 5, 6, 7]

7. IF-ELSE WITH STRINGS
Modified words: ['apple', 'BANANA', 'CHERRY', 'date', 'ELDERBERRY']

List comprehension practice complete!
🏆

Certificate of Completion

You have completed the Python List Comprehension tutorial. You now understand basic syntax, conditional filtering, if-else in comprehension, nested comprehension, and performance considerations.

Quiz

Test your understanding of list comprehension:

1. What is the correct syntax for list comprehension?
2. What does the if clause at the end of a list comprehension do?
3. What is the difference between if at the end and if-else in expression?
4. Does list comprehension modify the original list?
5. When should you avoid using list comprehension?

Frequently Asked Questions

What is list comprehension in Python? ▼

List comprehension is a concise syntax for creating lists by applying an expression to each element of an iterable. It is more readable and often faster than traditional for loops for simple operations.

What is the difference between if at the end and if-else in comprehension? ▼

if at the end filters elements: [x for x in list if condition]. if-else in expression transforms elements: [x if condition else y for x in list]. The former filters; the latter transforms.

Is list comprehension faster than a for loop? ▼

Yes, list comprehension is generally faster because it is implemented in C and optimized for list creation. However, the performance difference is only significant for large datasets.

Can I have multiple if conditions in list comprehension? ▼

Yes, you can have multiple if conditions using and/or operators or multiple if clauses. For example: [x for x in list if x > 0 and x < 10].

Does list comprehension modify the original list? ▼

No, list comprehension creates a new list and does not modify the original list. The original iterable remains unchanged.

When should I NOT use list comprehension? ▼

Avoid list comprehension when the logic is complex, when you need side effects (like printing), when you need multiple operations, or when readability would suffer. Use regular loops for complex operations.

Next Steps

After mastering list comprehension, consider exploring these related topics:

List Functions

Essential methods for list manipulation: append, pop, sort, and more.

Learn More →

Dictionary Comprehension

Create dictionaries concisely using comprehension syntax.

Learn More →

Set Comprehension

Create sets using comprehension syntax.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • Python Data Types Interview Questions
Previous: List Functions Next: List Assignments →