Python List comprehension
Table of Contents
Description
List comprehension is a concise and elegant way to create lists using a single line of code. It is more readable and faster than traditional for loops in many scenarios.
Syntax:
[expression for item in iterable if condition]
Prerequisites
- Understanding of loops (especially for loops)
- Familiarity with list data type
- Basic knowledge of if conditions and expressions
Examples
Here's a simple program in Python:
# Basic example: Generate a list of numbers from 0 to 4 numbers = [x for x in range(5)] # [0, 1, 2, 3, 4] # With condition: Get even numbers from 0 to 9 evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8] # With operation: Square of each number from 1 to 5 squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25] # Using if-else in comprehension labels = ['even' if x % 2 == 0 else 'odd' for x in range(5)] # ['even', 'odd', 'even', 'odd', 'even'] # Nested comprehension: Flatten a 2D list matrix = [[1, 2], [3, 4]] flattened = [num for row in matrix for num in row] # [1, 2, 3, 4]Real-World Applications
Data cleaning: Filter or modify elements in a dataset
Web scraping: Extract and filter results from HTML pages
Mathematical operations: Perform transformations on numeric lists
Text processing: Convert, clean, or filter strings in a list
Configuration parsing: Create structured data from raw input
Where topic Can Be Applied
Data Science: Efficiently filter or transform datasets
Web Development: Prepare lists for rendering (e.g., dropdowns)
Scripting: File handling, renaming, log extraction
NLP: Token cleanup, stop word removal, case conversion
Automation: Quick transformations in config or response data
Resources
WatchTopic video source
A comprehensive video
VisitPython pdf
pdf on topic
Interview Questions
What is list comprehension and how does it work?
How is list comprehension different from a regular loop?
Can we use if-else inside list comprehensions? Give an example
How do you flatten a 2D list using list comprehension?/p>
What are the limitations of list comprehensions?