Python List Comprehension: Syntax, Examples & Real-World Uses
Learn Python list comprehension with clear syntax, beginner-friendly examples, and real-world applications. Discover how to write concise, efficient code for data processing, filtering, and transformations.
Table of Contents
- What is List Comprehension?
- Why Use List Comprehension?
- Basic Syntax
- Examples for Beginners
- Real-Life Usage Examples
- When Not to Use List Comprehension
- Tasks
- Practice & Progress
1. What is List Comprehension?
List comprehensions are a shorter and cleaner way to create lists. Instead of writing multiple lines with a for loop, you can do the same in just one line.
2. Why Use List Comprehension?
- Readability: Once you're familiar with the syntax, list comprehensions are often more readable than equivalent loop constructs.
- Conciseness: They allow you to express complex operations in a single line.
- Performance: List comprehensions can be slightly faster than equivalent
forloops in many cases. - Pythonic: They are considered a more "Pythonic" way to create lists.
3. Basic Syntax
[expression for item in iterable if condition]expression: What you want to do with each itemitem: The variable representing each element in the iterableiterable: The sequence you're looping through (list, tuple, string, etc.)condition(optional): Filters which items to include
4. Examples for Beginners
Example 1: Basic transformation
# Traditional way
numbers = [1, 2, 3, 4]
squares = []
for num in numbers:
squares.append(num ** 2)
# With list comprehension
squares = [num ** 2 for num in numbers]
# Result: [1, 4, 9, 16]Python List Comprehension Tutorial โ Easy Code Example and Video for Beginners
Example 2: Filtering
# Only even numbers
numbers = [1, 2, 3, 4, 5, 6]
evens = [num for num in numbers if num % 2 == 0]
# Result: [2, 4, 6]๐ means: โFrom numbers 1 to 6, pick x only if x is evenโ
Example 3: Combining transformation and filtering
# Squares of even numbers only
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [num ** 2 for num in numbers if num % 2 == 0]
# Result: [4, 16, 36]5. Real-Life Usage Examples
1. Processing user input
# Convert comma-separated string to list of integers
user_input = "1, 2, 3, 4, five, 6"
numbers = [int(x.strip()) for x in user_input.split(',') if x.strip().isdigit()]
# Result: [1, 2, 3, 4, 6]2. Data cleaning
# Remove empty strings and strip whitespace
data = [" apple ", "banana", " ", "cherry ", ""]
clean_data = [fruit.strip() for fruit in data if fruit.strip()]
# Result: ["apple", "banana", "cherry"]3. Working with files
# Read lines from a file and remove newline characters
with open('data.txt') as file:
lines = [line.strip() for line in file]4. Matrix operations
# Transpose a matrix (swap rows and columns)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(3)]
# Result: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]5. API response processing
# Extract specific fields from API response
api_response = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True}
]
active_users = [user["name"] for user in api_response if user["active"]]
# Result: ["Alice", "Charlie"]6. When Not to Use List Comprehension
While list comprehensions are powerful, they're not always the best choice:
- When the logic is too complex (becomes hard to read)
- When you need to use multiple conditions that would make the comprehension too long
- When you need to include side effects (like printing) during iteration
In these cases, a traditional for loop might be more appropriate.
7. Tasks
Task 1: Square all numbers
Create a list of numbers from 1 to 10. Use list comprehension to generate a new list with the square of each number.
# Expected Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Task 2: Filter odd numbers
From a list of numbers, create a new list containing only the odd numbers using list comprehension.
# Input: [10, 15, 20, 25, 30, 35]
# Expected Output: [15, 25, 35]Task 3: Cube of even numbers
Use list comprehension to get the cube of even numbers from the list.
# Input: [1, 2, 3, 4, 5, 6]
# Expected Output: [8, 64, 216]Task 4: Multiply by 10 if number is divisible by 5
Write a list comprehension to multiply only the numbers divisible by 5 by 10.
# Input: [5, 8, 10, 13, 20, 21]
# Expected Output: [50, 100, 200]Task 5: Replace even numbers with "Even"
Replace all even numbers in a list with the string "Even" using list comprehension.
# Input: [3, 6, 9, 12, 15]
# Expected Output: [3, 'Even', 9, 'Even', 15]Task 6: Create a list of first letters
Given a list of names, create a list of the first letter of each name using list comprehension.
# Input: ["Alice", "Bob", "Charlie"]
# Expected Output: ['A', 'B', 'C']Task 7: Convert all strings to uppercase
Convert each string in a list to uppercase using list comprehension.
# Input: ["apple", "banana", "cherry"]
# Expected Output: ["APPLE", "BANANA", "CHERRY"]8. Practice & Progress
1. Multiple-Choice Questions (MCQs)
- A set of questions with multiple answer options to test your understanding of Python concepts, syntax, or expected outcomes. Ideal for assessing your knowledge in a structured format.