Meaning
Creates a new list containing only the elements of an existing iterable that satisfy a condition, using a list comprehension. It returns a new list, leaving the original iterable unchanged. This is ideal for filtering data in a concise, readable way.
Primary Function
Data filtering
Communicative Purpose
Select elements that meet a predicate while constructing a list in a concise, readable way.
Pattern
[expression for item in iterable if condition]
Core Structure
[ ... for ... in ... if ... ]
Função primária
Data filtering
Propósito comunicativo
Select elements that meet a predicate while constructing a list in a concise, readable way.
Situações de gatilho
When you need to extract even numbers from a list; when you want to keep items that match a predicate without mutating the original list.
Contextos
General‑purpose Python scripts, data‑processing pipelines, algorithm implementations.
Padrão
[expression for item in iterable if condition]
Estrutura central
[ ... for ... in ... if ... ]
Slots de substituição
output_expr: expression, loop_var: identifier, iterable: expression, predicate: expression
Colocados típicos
- if condition
- for loop_var in iterable
- list literals
Substituições comuns
- Using filter() with a lambda
- using an explicit for‑loop with append()
Erros comuns
Omitting the if clause, forgetting the surrounding brackets (producing a generator expression instead of a list), introducing side‑effects in the expression part.
Similar / contraste
filter() returns an iterator, while a list comprehension creates a list immediately; a generator expression (parentheses) is lazy and memory‑efficient compared to a list comprehension (brackets).
Interferências
Coming from JavaScript: using map() for filtering is incorrect; assuming list comprehensions always produce a list—generator expressions require parentheses.
Família do chunk
- list comprehension
- generator expression
- filter
- map
Nuance
List comprehensions evaluate eagerly, which can be costly for very large data; prefer a generator expression or itertools.filterfalse for lazy evaluation.
Efeito pragmático
Makes code concise and expressive; eliminates boilerplate loops and manual list appends; reduces risk of forgetting to initialize the list.
Dica de memória
Even numbers list comprehension: filtered = [x for x in my_list if x % 2 == 0]
Nota
List comprehensions are eager and create a new list; for large or infinite data prefer generator expressions or itertools.filterfalse for lazy evaluation.
Upgrade path
Use a generator expression for lazy evaluation: filtered = (x for x in my_list if x % 2 == 0)
Log in to save chunks.