0
0
Pythonprogramming~5 mins

List comprehension with if–else in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is list comprehension with if–else in Python?
It is a way to create a new list by applying a condition to each item, choosing one value if the condition is true and another if false, all in one line.
Click to reveal answer
beginner
How do you write a list comprehension with if–else?
Use the syntax: [ if <condition> else for <item> in <iterable>].
Click to reveal answer
beginner
Example: What does this code do? [x*2 if x > 5 else x+2 for x in range(8)]
It creates a list where numbers greater than 5 are doubled, and numbers 5 or less have 2 added. Result: [2, 3, 4, 5, 6, 7, 12, 14]
Click to reveal answer
intermediate
Can you use if–else inside list comprehension without an else part?
No, if you want to choose between two values, you must include else. But you can filter items with if alone (no else) to include only some items.
Click to reveal answer
beginner
Why use list comprehension with if–else instead of a for loop?
It makes code shorter and easier to read by combining looping and conditional logic in one line.
Click to reveal answer
What is the correct syntax for list comprehension with if–else?
A[value_if_true if condition else value_if_false for item in iterable]
B[value_if_true for item in iterable if condition else value_if_false]
C[if condition value_if_true else value_if_false for item in iterable]
D[value_if_true else value_if_false if condition for item in iterable]
What will this list comprehension produce? [x+1 if x % 2 == 0 else x-1 for x in range(4)]
A[2, 1, 4, 3]
B[1, 2, 3, 4]
C[0, 1, 2, 3]
D[1, 0, 3, 2]
Can you omit the else part in a list comprehension with if–else?
AYes, else is optional
BNo, else is required if using if–else
CYes, but only for strings
DNo, unless you use a for loop
Which of these is a valid use of if in list comprehension without else?
A[x for x in range(5) if x > 2]
B[x if x > 2 for x in range(5)]
C[x if x > 2 else 0 for x in range(5)]
D[if x > 2 x for x in range(5)]
Why might you choose list comprehension with if–else over a for loop?
AIt is always faster
BIt uses less memory
CIt makes code shorter and clearer
DIt avoids using variables
Explain how to use if–else inside a list comprehension and give a simple example.
Think about how you pick one value if true and another if false for each item.
You got /3 concepts.
    Describe the difference between using if alone and if–else in list comprehensions.
    Consider when you want to include or exclude items versus when you want to transform items differently.
    You got /3 concepts.