Which of the following statements about Python list comprehensions is true?
Understanding Python List Comprehensions
Option 1 – Incorrect: List comprehensions can create lists of any type, including strings, objects, or mixed data types.
Option 2 – Incorrect: The for loop is written inside the brackets, not outside.
Option 3 – Incorrect: Conditional statements can be included using if or if-else.
Option 4 – Correct: List comprehensions provide a concise syntax to generate lists from any iterable, optionally applying conditions or transformations.
Example:
# Squares of even numbers from 1 to 5
squares = [x**2 for x in range(1,6) if x % 2 == 0]
print(squares) # Output: [4, 16]
Step-by-step reasoning:
Loop through numbers 1 to 5.
Include only even numbers (x % 2 == 0).
Square each number (x**2) and add to the list.
Resulting list → [4, 16]
Key takeaways:
List comprehensions are a concise alternative to traditional loops.
They can include transformations and optional filtering.
Useful for creating new lists from existing iterables efficiently.
What is the output of the following code?
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers]
print(squared)
Understanding simple list comprehensions for transformations
Option 1 – Incorrect: This is the original list, no transformation applied.
Option 2 – Correct: Each number in the list is squared using x**2.
Option 3 – Incorrect: This would be obtained by multiplying each number by 2 (x*2), not squaring.
Option 4 – Incorrect: This is the cube of each number (x**3), not square.
Step-by-step reasoning:
Iterate through each element in numbers: 1, 2, 3, 4, 5.
Square each element using x**2.
Build a new list with squared values → [1, 4, 9, 16, 25].
Key takeaways:
List comprehensions can transform each element in an iterable concisely.
Syntax: [expression for item in iterable]
Useful for mapping operations without using explicit loops.
Which of the following statements about conditions in Python list comprehensions is true?
Understanding conditions in list comprehensions
Option 1 – Incorrect: Conditions usually come after the iteration expression (for x in iterable), not necessarily after the output expression.
Option 2 – Incorrect: Multiple conditions can be combined using logical operators like and or or.
Option 3 – Incorrect: You can use if-else inline within list comprehensions for conditional outputs.
Option 4 – Correct: List comprehensions support optional conditions to filter elements or transform them based on a condition.
Example:
# Mark numbers as 'Even' or 'Odd'
numbers = [1, 2, 3, 4]
labels = ['Even' if x % 2 == 0 else 'Odd' for x in numbers]
print(labels) # Output: ['Odd', 'Even', 'Odd', 'Even']
Step-by-step reasoning:
Iterate through each element in numbers.
Check condition x % 2 == 0.
If true → 'Even', else → 'Odd'.
Build a new list → ['Odd', 'Even', 'Odd', 'Even'].
Key takeaways:
List comprehensions can include inline conditions for filtering or transforming elements.
Syntax for conditional expressions: [expression_if_true if condition else expression_if_false for item in iterable]
Useful for concise and readable conditional transformations.
What is the output of the following code snippet?
numbers = [0, 1, 2, 3, 4]
doubled = [x*2 for x in numbers if x % 2 == 0]
print(doubled)
Filtering and transforming elements in a list comprehension
Option 1 – Incorrect: This doubles all numbers without filtering; the code filters only even numbers.
Option 2 – Incorrect: This only lists odd numbers without doubling.
Option 3 – Correct: Doubles only even numbers (0, 2, 4) → [0, 4, 8].
Option 4 – Incorrect: This would correspond to doubling odd numbers, which is not done here.
Step-by-step reasoning:
Iterate through numbers: 0, 1, 2, 3, 4.
Filter only even numbers using if x % 2 == 0 → 0, 2, 4.
Double each filtered number using x*2 → 0*2=0, 2*2=4, 4*2=8.
Resulting list → [0, 4, 8].
Key takeaways:
List comprehensions can combine filtering and transformation in a single line.
Order: filter comes after the iteration expression (for x in iterable).
This syntax is concise and avoids using multiple loops or temporary lists.
What is the output of the following code snippet?
words = ["apple", "banana", "cherry"]
lengths = [len(word) for word in words]
print(lengths)
Using list comprehensions to calculate lengths of strings
Option 1 – Incorrect: The length of 'apple' is 5, not 4.
Option 2 – Incorrect: 'cherry' has 6 letters, not 6? Actually, let's check carefully.
Option 3 – Correct: Lengths are calculated as follows:
'apple' → 5
'banana' → 6
'cherry' → 6
Resulting list → [5, 6, 6].
Option 4 – Incorrect: All lengths are not 6.
Step-by-step reasoning:
Iterate through each word in words: 'apple', 'banana', 'cherry'.
Calculate len(word) for each:
'apple' → 5
'banana' → 6
'cherry' → 6
Build new list → [5, 6, 6].
Key takeaways:
List comprehensions can apply any function or operation to each element of an iterable.
Concise syntax avoids using explicit loops.
Useful for mapping transformations over sequences.
Which of the following statements about nested list comprehensions is true?
Understanding nested list comprehensions
Option 1 – Incorrect: Conditional statements can be included in nested comprehensions.
Option 2 – Correct: Nested list comprehensions allow placing one comprehension inside another, which is useful for handling multidimensional data like matrices.
Option 3 – Incorrect: Nested comprehensions do not automatically flatten nested lists; explicit flattening is required.
Option 4 – Incorrect: Nested comprehensions can iterate over any iterable, not just numbers.
Example:
# Flattening a 2x2 matrix using nested comprehension
matrix = [[1, 2], [3, 4]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4]
Step-by-step reasoning:
Outer comprehension iterates through each row in matrix.
Inner comprehension iterates through each number in the row.
Each number is added to the new flattened list → [1, 2, 3, 4].
Key takeaways:
Nested comprehensions are powerful for handling multidimensional data.
They can include multiple iterables and optional conditions.
Flattening or mapping data structures is concise using nested comprehensions.
What is the output of the following code snippet?
numbers = [1, 2, 3, 4, 5]
result = [x for x in numbers if x > 3]
print(result)
Filtering elements using conditions in list comprehensions
Careful placement of conditions ensures correct filtering and avoids nested structures if flattening is required.
Quick Recap of Python List Comprehensions Concepts
If you are not clear on the concepts of List Comprehensions, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.
What Are List Comprehensions in Python
A list comprehension in Python is a compact and readable way to create a new list by transforming or filtering items from an existing iterable (like a list, tuple, string, or range) using Python keywords such as for, if, and in. Instead of writing a full for loop with .append(), you can generate the result in a single line.
Syntax:
[expression for item in iterable if condition]
expression — how to transform each item
item — the loop variable
iterable — the collection you iterate over
if condition (optional) — filter items based on a condition
Flexible — supports transformation, filtering with if, nested for loops, and expressions using Python keywords like len(), str(), int(), etc.
Basic Examples of List Comprehension
Some simple examples using Python keywords like for and in:
# Example 1: Square numbers using for and in
numbers = [2, 4, 6, 8]
squared = [n ** 2 for n in numbers] # [4, 16, 36, 64]
# Example 2: Generate list from range
nums = [i for i in range(10)] # [0,1,2,3,4,5,6,7,8,9]
# Example 3: Convert string to uppercase characters
chars = [ch.upper() for ch in "Python"] # ['P','Y','T','H','O','N']
Filtering Items Using Python Keywords
You can filter items with an if condition inside the list comprehension:
# Keep even numbers only
evens = [n for n in range(1, 11) if n % 2 == 0] # [2,4,6,8,10]
# Conditional transformation with if-else
labels = ["even" if n % 2 == 0 else "odd" for n in range(1, 11)]
# ['odd','even','odd','even',...]
Nested Loops and Complex List Comprehensions
Use nested for loops and comprehensions to combine items from multiple iterables or flatten data structures:
# Example: all (x, y) pairs for x in range and y in range
pairs = [(x, y) for x in range(3) for y in range(3)]
# [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
# Example: flatten a matrix (list of lists)
matrix = [[1,2,3], [4,5,6], [7,8,9]]
flat = [val for row in matrix for val in row] # [1,2,3,4,5,6,7,8,9]
When and When Not to Use List Comprehensions
Use list comprehensions when:
Transforming or filtering data in one step
Building new lists from iterables (list, tuple, string, range)
Logic is simple or moderately complex
Avoid when:
Logic becomes too complex with multiple nested loops or conditions
Side-effects are needed (printing, I/O, modifying external state) — regular for loops are better
Summary: Key Takeaways
List comprehensions in Python create lists in a concise and readable way
Combine for, if, else, and in in a single expression
Ideal for creating new lists from existing data efficiently
Use them when logic is simple and clear; avoid overcomplicating
Practicing Python List Comprehensions? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python List Comprehensions Exercises
Welcome to Solviyo’s Python List Comprehensions exercises, designed to help you master one of Python’s most elegant and powerful features. List comprehensions allow you to create new lists concisely, replace traditional loops, and write clean, efficient Python code. These exercises provide step-by-step practice with explanations and interactive Python MCQs to ensure a deep understanding.
What You Will Learn
In this set of Python List Comprehensions exercises, you will explore:
Creating simple list comprehensions to transform existing lists.
Applying conditional filters within list comprehensions.
Using nested list comprehensions for more complex transformations.
Combining functions with list comprehensions to manipulate data efficiently.
Understanding real-world applications such as generating sequences, filtering datasets, and transforming data structures.
Recognizing common mistakes and learning best practices for clean, efficient code.
Reinforcing learning through interactive Python MCQs and step-by-step explanations.
Why Learning Python List Comprehensions Matters
List comprehensions are essential for writing concise, readable, and efficient Python code. Mastering them will improve your problem-solving skills, enable faster data transformations, and prepare you for coding interviews, academic tasks, and professional projects. Understanding both basic and advanced techniques ensures you can tackle a wide range of Python problems effectively.
Start Practicing Python List Comprehensions Today
By completing these exercises, you will gain confidence in using list comprehensions to write clean, optimized Python code. Each exercise includes explanations and answers to help you understand the reasoning behind solutions. Start practicing Python List Comprehensions exercises now, and strengthen your Python programming skills while preparing for real-world coding challenges.
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.