📚 Quick Study Guide
🔍 Definition: List comprehensions provide a concise way to create lists based on existing lists or iterables.
💡 Syntax: `[expression for item in iterable if condition]` (the `if` condition is optional).
📝 Expression: The expression that's evaluated for each item.
🧮 Iterable: The sequence (e.g., list, tuple, range) being iterated over.
📌 Condition: An optional filter that includes only items satisfying the condition.
💫 Benefit: Often more readable and faster than traditional `for` loops for creating lists.
🐍 Pythonic: List comprehensions are considered a very Pythonic way to write code.
🧪 Practice Quiz
1. What is the output of the following list comprehension?
`[x
2 for x in range(5)]`
A. `[0, 1, 2, 3, 4]`
B. `[1, 4, 9, 16, 25]`
C. `[0, 1, 4, 9, 16]`
D. `[0, 1, 4, 9, 16, 25]`
2. Which of the following list comprehensions correctly filters even numbers from a list?
A. `[x for x in numbers if x % 2]`
B. `[x for x in numbers if x % 2 == 0]`
C. `[x if x % 2 == 0 for x in numbers]`
D. `[x % 2 == 0 for x in numbers]`
3. What does this list comprehension do? `[c.upper() for c in "hello"]`
A. Prints "hello" in uppercase.
B. Returns a string "HELLO".
C. Returns a list of uppercase characters: `['H', 'E', 'L', 'L', 'O']`
D. Raises an error.
4. What is the value of `new_list` after running this code?
python
numbers = [1, 2, 3, 4, 5]
new_list = [num * 2 for num in numbers if num > 2]
A. `[2, 4, 6, 8, 10]`
B. `[6, 8, 10]`
C. `[3, 4, 5]`
D. `[4, 6, 8]`
5. Which of the following is NOT a valid use case for list comprehensions?
A. Creating a new list with modified elements from an existing list.
B. Filtering elements from a list based on a condition.
C. Performing complex calculations that require multiple nested loops.
D. Creating a list of tuples from two different lists.
6. How can you create a list of the squares of odd numbers between 1 and 10 (inclusive) using list comprehension?
A. `[x2 for x in range(1, 11) if x % 2 == 1]`
B. `[x
2 for x in range(1, 10) if x % 2 == 0]`
C. `[x2 if x % 2 == 1 for x in range(1, 11)]`
D. `[x**2 for x in range(1, 11)] if x % 2 == 1`
7. What will be the output of the following code?
python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)
A. `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`
B. `[1, 2, 3, 4, 5, 6, 7, 8, 9]`
C. `[3, 6, 9]`
D. `[1, 4, 7]`
Click to see Answers
- C
- B
- C
- B
- C
- A
- B