15. Comprehension with if
A list comprehension can keep only the elements that satisfy a condition by adding if at the end:
condition— a boolean expression that usesitem.- When it is
True,expressionis added to the new list; when it isFalse, the element is skipped. - This is a filter: the result has the same or fewer elements, never more.
Coming from JavaScript? Adding if is .filter(): [n for n in numbers if n % 2 == 0] is numbers.filter(n => n % 2 === 0). Map and filter can be combined in one comprehension.
Keep the even numbers
Build a list comprehension with the even numbers of range(6) using if, then print the new list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Keep the long words
Use words = ["sun", "python", "code", "hi"]. Build a list comprehension that keeps only the words with more than 3 characters, then print the new list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Square the odd numbers
Build a list comprehension with the square of each odd number in range(6), then print the new list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Filter and transform
Build a list comprehension that multiplies by 10 each number of range(5) greater than 2, then print the new list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.