0
0
Pythonprogramming~5 mins

List comprehension with condition in Python

Choose your learning style9 modes available
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.
When you want to filter out unwanted items from a list.
When you want to create a list of squares of only even numbers from another list.
When you want to quickly make a list of words that start with a certain letter.
When you want to transform items but only if they meet a certain rule.
Syntax
Python
new_list = [expression for item in old_list if condition]
The 'expression' is what you want to put in the new list for each item.
The 'condition' is a test that decides if the item should be included.
Examples
Creates a list of even numbers from the original list.
Python
numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0]
Filters words that start with the letter 'a'.
Python
words = ['apple', 'banana', 'cherry', 'date']
a_words = [word for word in words if word.startswith('a')]
Works fine even if the original list is empty; result is an empty list.
Python
empty_list = []
filtered = [x for x in empty_list if x > 0]
Works with a list of one item, includes it if condition is true.
Python
single_item = [10]
filtered_single = [x for x in single_item if x > 5]
Sample Program
This program takes a list of numbers, then creates a new list with squares of only the even numbers, and prints both lists.
Python
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)
OutputSuccess
Important Notes
Time complexity is O(n), where n is the number of items in the original list.
Space complexity is O(m), where m is the number of items that meet the condition.
A common mistake is forgetting the 'if' condition, which includes all items instead of filtering.
Use list comprehension with condition when you want a quick, readable way to filter and transform lists.
Summary
List comprehension with condition lets you make a new list by choosing items that pass a test.
It makes your code shorter and easier to understand than using loops and if statements.
It works well even with empty lists or lists with one item.