Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › Python list comprehension: how to transform and filter lists

Python list comprehension: how to transform and filter lists

List comprehension is a Python syntax for building a new list from an iterable while applying a transformation and an optional filter in one expression. The general form is `[expression for item in iterable if condition]`, always in square brackets. It is a preparation tool: it organizes values before analysis with pandas or NumPy.

Topics: python, list-comprehension, fundamentos

What is list comprehension and what is the basic syntax?

List comprehension builds a new list from another sequence — a list, a string, a `range`, a tuple, or any iterable — without writing a loop with `append`. The structure has three parts: the expression that generates each item, the `for` clause, and an optional `if` filter at the end.

A simple example: `squares = [n ** 2 for n in range(6)]` returns `[0, 1, 4, 9, 16, 25]`. The equivalent loop would require creating an empty list, iterating over the range, and calling `append` on each pass.

The result is always a new object. In Python 3, the loop variable does not leak into the outer scope, so using `n` after the expression does not return the last value that was iterated.

How do you transform each item in a list?

The expression before the `for` receives each item and returns the value that enters the list. It can be arithmetic, a string method, a standard-library function, or a user-defined function.

To normalize text: `names = [n.strip().title() for n in raw_names]`. To convert types: `values = [float(v) for v in texts]`. To round measurements: `[round(x, 2) for x in measurements]`.

Calling your own function follows the same logic: `[classify(v) for v in sales]` runs `classify` once per item. If the function returns `None`, the list keeps `None` at that position — without an `if`, nothing is dropped.

`list(map(float, texts))` reaches the same result for the conversion. A comprehension tends to be more readable when there is also a filter or a compound transformation on the same line.

How do you filter items with if inside the comprehension?

An `if` at the end of the expression works as a filter: only the item that passes the test enters the list. `[n for n in numbers if n > 0]` keeps the positive values and drops zero and negatives.

Filters can be combined with `and`: `[p for p in products if p['stock'] > 0 and p['active']]`. Each condition is evaluated per item, from left to right.

The position of the `if` changes the meaning. The filter comes after the `for` and can remove items. The `if/else` conditional comes before the `for`, as an expression, and every item enters the list: `['even' if n % 2 == 0 else 'odd' for n in numbers]`.

When is a regular for loop the better choice?

List comprehension is not mandatory. It loses when the expression has a side effect, such as `print`, writing to a file, or calling an API. In that case, an explicit `for` loop makes clear that the goal is the effect, not the list.

It also loses when conditions and nesting pile up. `[x for sub in matrix for x in sub if x]` is valid, but it demands careful reading; with three levels, the traditional loop is clearer.

Memory is another criterion. The comprehension builds the whole list before returning it. If you only need a sum or a maximum, a generator expression avoids storing everything: `sum(x * x for x in numbers)`, with parentheses instead of square brackets.

Finally, debugging. An error inside a comprehension points to the whole line; in a `for` loop with separate steps, you can inspect each step.

How do you use list comprehension when preparing data for pandas?

Before creating a `DataFrame`, a comprehension helps build and clean the structure that will be loaded. A common pattern is to generate a list of dictionaries: `records = [{'date': d, 'value': float(v)} for d, v in zip(dates, values)]`, then pass `pd.DataFrame(records)`.

The same idea works for cleaning: strip whitespace, standardize case, discard records without a value, and convert text columns to numbers. `[r for r in records if r['value'] is not None]` filters before loading, so the `DataFrame` starts smaller.

The limit is volume. With many records, the intermediate list uses memory, and equivalent pandas operations may be more efficient. Choose among a list, NumPy, and pandas based on the size and the operation, and test with real data.

If you want structured practice with these patterns, the Python for Data Science and Analytics course at python.paanalytics.net starts from zero and covers loops, conditionals, basic functions, user-defined functions, NumPy, pandas, data cleaning and preparation, and outlier detection. It has three main modules — Basic, Intermediate, and Advanced — plus bonus modules, recorded lessons you can watch at your own pace, guided exercises, and real-world projects to build a portfolio.

The course closes with an end-to-end final project covering exploratory analysis and machine learning, including linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection, and cross-validation. It includes a certificate of completion, an exclusive community for networking, and permanent access with no expiration date. The price is R$ 470, or 12 payments of R$ 20.37 on the card, through the Hotmart checkout, which also accepts boleto. You do not need to know how to program before you start.

See the Python for Data Science and Analytics course

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Does list comprehension return a list or a generator?

It returns a list. A generator expression uses parentheses instead of square brackets and produces values lazily, one at a time. Use a generator when you only need to iterate once or feed a function such as `sum`, `max`, or `min`.

Can I use if/else inside list comprehension?

Yes. The `if/else` is a conditional expression placed before the `for`, and every item produces a value. A filter `if` placed after the `for` can remove items from the result. The two positions have different effects.

Is list comprehension faster than a for loop?

It can be faster in common cases, but that is not guaranteed for every operation. Readability, memory use, and the work done inside the expression also matter. If performance is critical, measure the alternatives with your own data.

Can I use list comprehension with a pandas DataFrame?

It returns a Python list, so it is useful for building records before `pd.DataFrame()` or for preprocessing rows outside pandas. For operations on existing columns, vectorized pandas and NumPy methods are often clearer and may use less memory. Test with your data.

Do I need to know programming before learning list comprehension?

No prior programming knowledge is required to start the course. List comprehension is easier after you see variables, loops, conditionals, and functions, and the course covers those basics before moving into NumPy, pandas, and data preparation.

Ler em português →