0
0
PythonHow-ToBeginner · 3 min read

How to Filter a List in One Line in Python

You can filter a list in one line in Python using a list comprehension like [x for x in list if condition] or the filter() function with a lambda, like list(filter(lambda x: condition, list)). Both methods create a new list containing only items that meet the condition.
📐

Syntax

There are two common ways to filter a list in one line:

  • List comprehension: [x for x in list if condition] creates a new list with elements x from the original list that satisfy the condition.
  • filter() function: list(filter(function, list)) applies function to each element and keeps those where the function returns True.
python
[x for x in my_list if condition]

list(filter(lambda x: condition, my_list))
💻

Example

This example shows how to filter a list of numbers to keep only even numbers using both methods.

python
my_list = [1, 2, 3, 4, 5, 6]

# Using list comprehension
filtered_list1 = [x for x in my_list if x % 2 == 0]

# Using filter() with lambda
filtered_list2 = list(filter(lambda x: x % 2 == 0, my_list))

print(filtered_list1)
print(filtered_list2)
Output
[2, 4, 6] [2, 4, 6]
⚠️

Common Pitfalls

Common mistakes when filtering lists include:

  • Forgetting to convert the result of filter() to a list, which returns a filter object instead of a list.
  • Using incorrect conditions that always return True or False, resulting in no filtering.
  • Modifying the original list inside the comprehension or filter function, which can cause unexpected behavior.
python
# Wrong: filter() returns an iterator, not a list
my_list = [1, 2, 3]
filtered = filter(lambda x: x > 1, my_list)
print(filtered)  # Prints a filter object, not the filtered list

# Right: convert filter object to list
filtered_correct = list(filter(lambda x: x > 1, my_list))
print(filtered_correct)
Output
<filter object at 0x7f...> [2, 3]
📊

Quick Reference

Use this quick guide to filter lists in one line:

MethodSyntaxDescription
List Comprehension[x for x in list if condition]Creates a new list with elements that meet the condition.
filter() Functionlist(filter(function, list))Filters elements where function returns True; convert to list.

Key Takeaways

Use list comprehensions for clear and concise one-line list filtering.
Remember to convert the filter() result to a list to see filtered elements.
Ensure your condition correctly reflects the filtering criteria.
Avoid modifying the original list while filtering to prevent bugs.