Concept
List Comprehensions with Conditionals
Filter items inside a list comprehension by sticking an `if` clause at the very end: `[x for x in data if condition]`.
python
nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
print(evens) # [2, 4, 6]
# 100. List Comprehensions with Conditionals Filter items inside a list comprehension by sticking an `if` clause at the very end: `[x for x in data if condition]`: ```python nums = [1, 2, 3, 4, 5, 6] evens = [n for n in nums if n % 2 == 0] print(evens) # [2, 4, 6] ``` Notice: To filter, put `if` at the end. If you want an if/else ternary transformation (`[a if cond else b for x in data]`), place it at the front before `for`.
Checkpoint
In `[x for x in nums if x > 10]`, what items make it into the new list?
Practice
From `scores = [45, 88, 92, 30, 75]`, create a list of passing scores (>= 70) using a comprehension with an `if` filter. Print the result.
01
Tap code blocks below to assemble
Available Blocks