1. Home
  2. Blog
  3. Software Development

Software Development

Python List Comprehension: Syntax, Examples and When to Avoid It

Learn Python list comprehension step by step: build, filter and transform lists in one line, see measured timings against loops, and know when a plain for loop reads better.

7 min read
Python list comprehension: syntax, examples and when to avoid it

Key takeaways

  • The pattern is [expression for item in iterable if condition].
  • Put a plain if at the end to filter, and an if-else at the front to choose between two values.
  • In our test a comprehension ran about 37% faster than a loop with append.
  • Switch to a generator expression for huge data, and to a normal loop when the logic needs more than one clear step.

A Python list comprehension builds a new list from any iterable in a single readable line. Instead of creating an empty list, looping and calling append, you describe the result you want.

This guide goes from the basic pattern to filters, nested loops and timings we measured ourselves. If Python is new to you, start with our Python tutorial for beginners and keep a clean setup with the virtual environment guide.

Python list comprehension syntax

Read it from left to right: the expression says what each new item looks like, the for part says where items come from.

squares = [x * x for x in range(6)]
print(squares)          # [0, 1, 4, 9, 16, 25]

names = [" Hi ", "  QA "]
clean = [n.strip().lower() for n in names]
print(clean)            # ['hi', 'qa']

The same result with a loop needs three more lines. That saving is the whole point, as long as the line stays easy to read.

Filter items with a condition

Add an if after the loop to keep only the items that pass.

evens = [x for x in range(10) if x % 2 == 0]
print(evens)            # [0, 2, 4, 6, 8]

Python list comprehension with if-else

When you want a value for every item, put the if-else before the for. This is the part most beginners get wrong, because a trailing else is a syntax error.

labels = ["even" if x % 2 == 0 else "odd" for x in range(4)]
print(labels)           # ['even', 'odd', 'even', 'odd']

Rule of thumb: an if at the end removes items, an if-else at the start changes items. The list length stays the same with if-else.

Nested loops and flattening

Several for clauses read in the same order as nested loops. Use them to flatten a list of lists or to pair values.

matrix = [[1, 2, 3], [4, 5, 6]]
flat = [n for row in matrix for n in row]
print(flat)             # [1, 2, 3, 4, 5, 6]

pairs = [(x, y) for x in range(1, 3) for y in "ab"]
print(pairs)            # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

To transpose the matrix, nest a comprehension inside another: [[r[i] for r in matrix] for i in range(3)] gives [[1, 4], [2, 5], [3, 6]]. Two levels is the practical limit before readability drops.

Dictionary, set and generator forms

Change the brackets and the same idea builds other types.

lengths = {w: len(w) for w in ["pip", "venv", "uv"]}   # {'pip': 3, 'venv': 4, 'uv': 2}
unique  = {len(w) for w in ["pip", "venv", "uv", "git"]}  # {2, 3, 4}
total   = sum(x * x for x in range(1_000_000))           # generator, no list

Compare the types themselves in our guide to lists, tuples, sets and dictionaries.

Speed and memory: what we measured

We timed each version on Python 3.13.6 with 100,000 integers, taking the best of five runs. Your numbers will differ, but the order is stable.

Task Time
Loop with append (double each item) 5.18 ms
List comprehension (double each item) 3.25 ms
list(map(lambda ...)) 6.50 ms
Filter evens with a loop 3.62 ms
Filter evens with a comprehension 3.43 ms

A comprehension beats the append loop clearly, while the gap shrinks when most of the time goes to the condition. On memory, a list of one million doubled integers took about 8.4 MB, while the matching generator object was 200 bytes, because it produces values one at a time.

When not to use a list comprehension

  • You only need side effects such as printing or saving. Use a normal loop; a comprehension would build a useless list.
  • The logic has several steps. If you need a second variable or a try, write a loop or a small function.
  • The data is huge. Use a generator expression so Python never holds the full list in memory.
  • It needs more than two for clauses. Split it into named steps for the next reader.

Final thoughts

Use a Python list comprehension when one short line says exactly what you mean, and a loop when it does not. Start with the basic pattern, add one filter, then try the if-else form until the order feels natural.

Frequently asked questions

What is a list comprehension in Python?

It is a compact way to create a list by applying an expression to each item of an iterable, with an optional condition to filter items.

How do I use if-else in a list comprehension?

Put the conditional expression before the for clause, for example ["even" if x % 2 == 0 else "odd" for x in nums]. A plain filter uses a single if after the loop.

Is a list comprehension faster than a for loop?

Usually yes. In our test with 100,000 items it ran about 37% faster than a loop that calls append, but readability should decide first.

What is the difference between a list comprehension and a generator expression?

A list comprehension builds the whole list in memory at once. A generator expression uses parentheses and produces one value at a time, which saves memory on large data.

Can I nest list comprehensions?

Yes, for flattening or transposing a matrix. Keep it to two levels, and switch to a loop if it becomes hard to read.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →