Introduction
List comprehension with condition helps you create a new list by picking only the items you want from another list, making your code shorter and easier to read.
Jump into concepts and practice - no test required
new_list = [expression for item in old_list if condition]
numbers = [1, 2, 3, 4, 5] even_numbers = [num for num in numbers if num % 2 == 0]
words = ['apple', 'banana', 'cherry', 'date'] a_words = [word for word in words if word.startswith('a')]
empty_list = [] filtered = [x for x in empty_list if x > 0]
single_item = [10] filtered_single = [x for x in single_item if x > 5]
numbers = [10, 15, 20, 25, 30] print('Original list:', numbers) even_squares = [num ** 2 for num in numbers if num % 2 == 0] print('Squares of even numbers:', even_squares)
[x for x in range(5) if x % 2 == 0]x % 2 == 0 selects numbers divisible by 2 (even numbers).nums?[expression for item in iterable if condition]. Here, expression and item are both x, iterable is nums, and condition is x > 10.nums = [3, 7, 12, 5, 20] result = [n*2 for n in nums if n > 6] print(result)
values = [1, 2, 3, 4] new_values = [x for x in values if x > 2 else 0]
[x if x > 2 else 0 for x in values].words = ['apple', '', 'banana', 'cherry', '', 'date']. Which list comprehension creates a new list with only non-empty strings in uppercase?if w filters out empty strings.w, w.upper() converts it to uppercase.