0
0
Pythonprogramming~5 mins

List comprehension with condition in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is list comprehension with condition in Python?
It is a way to create a new list by looping over an existing list and including only items that meet a certain condition.
Click to reveal answer
beginner
How do you write a list comprehension that includes only even numbers from a list nums?
Use:
[x for x in nums if x % 2 == 0]
This means: take each x in nums only if x is even.
Click to reveal answer
beginner
What happens if the condition in a list comprehension is always false?
The result is an empty list because no items meet the condition to be included.
Click to reveal answer
intermediate
Can you use multiple conditions in a list comprehension? How?
Yes, by combining conditions with and or or. Example:
[x for x in nums if x > 0 and x % 2 == 0] selects positive even numbers.
Click to reveal answer
beginner
Rewrite this code using list comprehension with condition:
result = []
for x in nums:
    if x > 10:
        result.append(x * 2)
Using list comprehension:
[x * 2 for x in nums if x > 10]
Click to reveal answer
What does this list comprehension do?
[x for x in range(5) if x != 3]
ACreates a list of numbers from 0 to 4 excluding 3
BCreates a list of numbers from 0 to 3
CCreates a list with only the number 3
DCreates an empty list
Which of these is a correct syntax for list comprehension with condition?
A[if x > 0 for x in nums]
B[x if x > 0 for x in nums]
C[x for x in nums if x > 0]
D[x for if x > 0 in nums]
What will be the output of [x*2 for x in [1,2,3] if x > 2]?
A[2, 4, 6]
B[6]
C[4, 6]
D[]
How can you filter out odd numbers from a list nums using list comprehension?
A[x for x in nums if x < 0]
B[x for x in nums if x % 2 == 1]
C[x for x in nums if x > 0]
D[x for x in nums if x % 2 == 0]
What does the condition part in list comprehension control?
AWhich items are included in the new list
BHow many times the loop runs
CThe order of items in the list
DThe type of items in the list
Explain how to use list comprehension with a condition to create a list of squares of even numbers from another list.
Think about filtering first, then applying the square.
You got /3 concepts.
    Describe what happens if the condition in a list comprehension never matches any item.
    What does an empty filter mean for the output?
    You got /3 concepts.