List comprehension is used to create new lists quickly and clearly. It makes code shorter and easier to read compared to using loops.
Why list comprehension is used in Python
Start learning this pattern below
Jump into concepts and practice - no test required
new_list = [expression for item in old_list if condition]
The expression is what you want to put in the new list for each item.
The if condition part is optional and filters which items to include.
numbers = [1, 2, 3, 4, 5] squares = [x * x for x in numbers]
numbers = [1, 2, 3, 4, 5] even_numbers = [x for x in numbers if x % 2 == 0]
empty_list = [] result = [x for x in empty_list]
single_item = [10] doubled = [x * 2 for x in single_item]
This program shows how to create a list of squares and a list of even numbers from the original list using list comprehension.
numbers = [1, 2, 3, 4, 5] print("Original list:", numbers) squares = [number * number for number in numbers] print("Squares using list comprehension:", squares) even_numbers = [number for number in numbers if number % 2 == 0] print("Even numbers using list comprehension:", even_numbers)
List comprehension is faster than using a for loop with append because it is optimized internally.
It uses more memory if the list is very large, so for huge data sets, consider using generators.
Common mistake: forgetting the brackets [] which makes it a generator expression, not a list.
List comprehension helps write shorter and clearer code to create lists.
It can both transform and filter items in one simple line.
It is a beginner-friendly way to work with lists efficiently.
Practice
list comprehension in Python?Solution
Step 1: Understand the purpose of list comprehension
List comprehension is designed to make list creation concise and readable.Step 2: Compare options with this purpose
Only To create lists in a shorter and clearer way says it helps create lists shorter and clearer, which matches the purpose.Final Answer:
To create lists in a shorter and clearer way -> Option DQuick Check:
List comprehension = shorter, clearer list creation [OK]
- Thinking it avoids loops completely
- Believing it makes code slower
- Assuming it makes code longer
Solution
Step 1: Recall list comprehension syntax
The correct syntax is: [expression for variable in iterable]Step 2: Check each option
[x**2 for x in range(1, 4)] matches the correct syntax; others have syntax errors or missing brackets.Final Answer:
[x**2 for x in range(1, 4)] -> Option BQuick Check:
Correct syntax = [x**2 for x in range(1, 4)] [OK]
- Placing 'for' after the expression
- Missing brackets around comprehension
- Using colon instead of brackets
nums = [1, 2, 3, 4] squares = [n*n for n in nums if n % 2 == 0] print(squares)
Solution
Step 1: Identify the list and condition
The list is nums = [1, 2, 3, 4]. The comprehension squares numbers only if they are even (n % 2 == 0).Step 2: Calculate squares of even numbers
Even numbers are 2 and 4. Their squares are 4 and 16.Final Answer:
[4, 16] -> Option AQuick Check:
Squares of even nums = [4, 16] [OK]
- Including odd numbers by mistake
- Returning original numbers instead of squares
- Confusing condition placement
result = [x*2 for x in range(5) if x > 2 else x]
Solution
Step 1: Understand list comprehension with condition
When using if-else inside list comprehension, it must be part of the expression, not after the for loop.Step 2: Identify the syntax error
The else clause after the if in the comprehension is invalid syntax here; it should be inside the expression part.Final Answer:
The else clause is not allowed in this position -> Option CQuick Check:
if-else must be inside expression, not after for [OK]
- Placing else after the for loop
- Confusing * with ** for multiplication
- Changing range unnecessarily
words = ['apple', '', 'banana', ' ', 'cherry']. Using list comprehension, how can you create a new list that contains only non-empty and non-blank words?Solution
Step 1: Understand the filtering requirement
We want to exclude empty strings and strings with only spaces (blank).Step 2: Analyze each option's filter
[word for word in words if word] excludes empty strings but keeps strings with spaces. [word for word in words if word != ''] excludes empty strings only. [word for word in words if word.strip()] usesstrip()to remove spaces and checks if anything remains, filtering out blanks. [word for word in words if len(word) > 1] excludes words of length 1 or less, which wrongly excludes single-letter words.Final Answer:
[word for word in words if word.strip()] -> Option AQuick Check:
Use strip() to remove blanks before filtering [OK]
- Only checking if word is non-empty, missing blanks
- Filtering by length incorrectly
- Not using strip() to remove spaces
