0
0
PythonHow-ToBeginner · 3 min read

How to Filter List Using List Comprehension in Python

You can filter a list in Python using list comprehension by adding a condition after the expression inside the brackets. The syntax is [expression for item in list if condition], which creates a new list with only the items that meet the condition.
📐

Syntax

The basic syntax for filtering a list using list comprehension is:

  • expression: the value to include in the new list (often the item itself)
  • item: each element from the original list
  • list: the original list you want to filter
  • condition: a test that each item must pass to be included

This syntax creates a new list with only the items where the condition is True.

python
[expression for item in list if condition]
💻

Example

This example shows how to filter a list of numbers to keep only the even ones using list comprehension.

python
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
Output
[2, 4, 6]
⚠️

Common Pitfalls

Common mistakes when filtering lists with list comprehension include:

  • Forgetting the if keyword before the condition.
  • Using assignment = instead of comparison == in the condition.
  • Modifying the original list inside the comprehension (which is not allowed).

Here is an example of a wrong and right way:

python
# Wrong: missing 'if'
numbers = [1, 2, 3, 4]
even = [num for num in numbers if num % 2 == 0]  # Correct syntax

# Right:
even = [num for num in numbers if num % 2 == 0]
📊

Quick Reference

Remember these tips when filtering lists with list comprehension:

  • Use if to filter items.
  • The expression can transform items if needed.
  • List comprehension creates a new list, original stays unchanged.

Key Takeaways

Use list comprehension with an if condition to filter lists in Python.
The syntax is [expression for item in list if condition] to create a new filtered list.
Always include the if keyword before the condition to avoid syntax errors.
List comprehension does not change the original list; it returns a new one.
You can also transform items while filtering by changing the expression part.