Python list comprehensions vs Java streams

A list comprehension does the work of stream().filter().map().toList() in one readable line. Here is how to read one, how every common stream operation maps to Python, and when a plain loop is the better choice.

Left, a Java sheet tagged 5 lines: a stream over docs that filters by score above 0.5, maps to text and collects to a list. An arrow points right to a dark Python sheet tagged 1 expression: texts equals d.text for d in docs if d.score above 0.5, in square brackets. Caption: read it: for, then if, then the front.
Fig. 1 — A five-line stream pipeline and the one-expression comprehension that does the same.

Java 8 gave you streams: filter, map, collect, and a whole vocabulary of collectors. Python’s answer is older and shorter: the comprehension, a way to build a new list (or dict, or set) from another one in a single expression.

The first time you see one, it looks backwards. Once you know the reading order, it reads like a sentence. And it’s everywhere: in data code, in AI code, and in anything an AI assistant writes for you.

This is part 8 of Python for Java Developers, and the first of the Python ideas that Java doesn’t have in this form. Part 7 covered exceptions.

A stream, and its comprehension

List<String> texts = docs.stream()
    .filter(d -> d.score() > 0.5)
    .map(d -> d.text())
    .toList();
texts = [d.text for d in docs if d.score > 0.5]

Same result: a new list holding the text of every document scoring above 0.5.

How to read a comprehension

Read it in this order: the for part first, then the if, then the front.

[d.text      for d in docs      if d.score > 0.5]
#  3. keep    1. for each d      2. only when
#  this                          this is true

“For each d in docs, if d.score is above 0.5, keep d.text.” The square brackets say the result is a list.

The if is optional. Without it, a comprehension is just a map:

squares = [n * n for n in range(5)]          # [0, 1, 4, 9, 16]
names = [user["name"] for user in users]     # pull one field out of a list of dicts
clean = [line.strip() for line in lines]

And it’s exactly equivalent to this loop, which you can always fall back to:

texts = []
for d in docs:
    if d.score > 0.5:
        texts.append(d.text)

Dict and set comprehensions

Swap the square brackets for braces. A dict comprehension has key: value at the front:

Map<String, Tool> byName = tools.stream()
    .collect(Collectors.toMap(Tool::name, t -> t));

Set<String> sources = hits.stream()
    .map(Hit::source)
    .collect(Collectors.toSet());
by_name = {tool.name: tool for tool in tools}

sources = {hit.source for hit in hits}

Unlike Collectors.toMap, a dict comprehension doesn’t throw on duplicate keys: the last value wins.

Without brackets: generator expressions

Drop the brackets inside a function call and you get a generator expression. It produces values one at a time instead of building a whole list first, like a lazy stream:

total_words = sum(len(c.split()) for c in chunks)
longest = max(len(line) for line in lines)

sum, max, min, any, all and "".join all accept one. For big inputs it saves memory; for small ones it just reads well. Generators get their own part later in the series.

Java stream operations, mapped to Python

Most stream pipelines have a short Python form, often a built-in function rather than a comprehension:

Java stream Python
.filter(p).map(f).toList() [f(x) for x in xs if p(x)]
.collect(toSet()) {f(x) for x in xs}
.collect(toMap(k, v)) {k(x): v(x) for x in xs}
.flatMap(x -> x.items().stream()) [i for x in xs for i in x.items]
.count() len(xs) or sum(1 for x in xs if p(x))
.anyMatch(p) any(p(x) for x in xs)
.allMatch(p) all(p(x) for x in xs)
.mapToInt(f).sum() sum(f(x) for x in xs)
.max(comparing(f)) max(xs, key=f)
.sorted(comparing(f)).toList() sorted(xs, key=f)
.limit(n) xs[:n]
.distinct() list(dict.fromkeys(xs)) (keeps order)
.findFirst() next((x for x in xs if p(x)), None)
.collect(joining(", ")) ", ".join(xs)
.collect(groupingBy(f)) a defaultdict(list) loop, below

Grouping is the one without a neat one-liner. The idiomatic version is a short loop:

from collections import defaultdict

by_dept = defaultdict(list)
for e in employees:
    by_dept[e.dept].append(e)

itertools.groupby exists too, but it only groups consecutive items, so the input must be sorted by the key first. Many Java developers get caught by that.

What about map() and filter()?

Python has map() and filter() built-in functions, and they work:

texts = list(map(lambda d: d.text, filter(lambda d: d.score > 0.5, docs)))

But Python developers almost always prefer the comprehension. It’s shorter, needs no lambdas, and reads left to right. If you find yourself chaining map and filter, write a comprehension instead.

Nested loops in a comprehension

Two for parts flatten nested data, like flatMap. They run in the same order as nested loops written out:

all_tags = [tag for doc in docs for tag in doc.tags]

# the same as:
all_tags = []
for doc in docs:
    for tag in doc.tags:
        all_tags.append(tag)

This is about the limit of what a comprehension should hold. Beyond it, readers struggle.

When to use a loop instead

Comprehensions are for building a collection. Use a normal loop when:

  • the logic needs more than one if or more than two for parts,
  • the line doesn’t fit on one line (or two, neatly wrapped),
  • you need side effects such as printing, writing to a database or calling an API,
  • you need try/except around each item.

AI-written code sometimes packs too much into one comprehension. It’s fine to unfold it into a loop while you read, and often better to keep it that way.

Key takeaways

  • [expr for x in items if cond] is filter + map + toList in one expression.
  • Read it in order: the for, then the if, then the front.
  • {k: v for ...} builds a dict, {x for ...} a set; duplicate dict keys keep the last value.
  • Without brackets inside a call, it’s a lazy generator expression: sum(x.size for x in items).
  • any, all, sum, max(key=), sorted(key=) and ", ".join cover most of the rest of the Stream API.
  • Group with a defaultdict(list) loop, and prefer a plain loop whenever a comprehension gets crowded.

Frequently asked questions

What is a list comprehension in Python?

An expression that builds a new list from an iterable: [expression for item in iterable if condition]. It does in one line what a loop with append does in four.

Is a list comprehension faster than a for loop?

Usually a little faster than the same loop with append, because it runs as one optimised operation. Choose it for readability, though, not speed: the difference rarely matters.

What is the Python equivalent of Java streams?

There’s no single one. Comprehensions cover filter and map, generator expressions give you laziness, and built-ins like sum, any, all, max, sorted and "".join cover the common terminal operations.

How do I do groupingBy in Python?

Loop over the items and append each one to a defaultdict(list) keyed by the group. itertools.groupby also works, but only on input already sorted by that key.

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

Square brackets build the whole list in memory right away. Round brackets (or none, inside a function call) create a generator that produces one value at a time when asked.

Next in the series: Python type hints vs Java generics, and why Python doesn’t enforce the types you write.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.