How do I conditionally unpack items in a Python comprehension?

November 18, 2026 4 answers
Asked by Ravmexo-6t

Python 3.15 supports starred unpacking in comprehension expressions. I tried putting a star on each branch of a conditional expression, but got a SyntaxError. How can I choose which iterable to unpack and then filter its elements?

Answers

Trelvani.8c

Put the conditional inside parentheses and unpack the result: [*(a if min(a) < 2 else a[::-1]) for a in items]. The star applies to the whole conditional expression, rather than separately to each branch.

To filter the flattened values too, you can wrap that comprehension: [b for b in [*(a if min(a) < 2 else a[::-1]) for a in items] if b % 2 == 0].

Zorvexa+3m:

That inner list is created before the outer comprehension filters it. If the data is large, a generator or a nested comprehension avoids that intermediate list.

Reply to this answer
_b46!queldaro.8

You can do the whole thing with an ordinary nested comprehension: [b for a in items for b in (a if min(a) < 2 else a[::-1]) if b % 2 == 0]. The first loop chooses each sequence, the second iterates over the chosen version, and the filter checks each individual value.

This doesn't need the new starred comprehension syntax and doesn't build a separate flattened list first.

Ravmexo-6t:

That makes the distinction clearer. The filter after the second loop applies to each value, not to each original sequence.

Reply to this answer
_q84+crankmuffin.2

If you don't need a list immediately, use a generator expression with the same nested loops: (b for a in items for b in (a if min(a) < 2 else a[::-1]) if b % 2 == 0). It produces values as you iterate, and you can pass it to list() later if needed.

Reply to this answer
Tavzino.4k

One readability point: if the selection and filtering get more complicated, a regular loop may be easier to maintain than a deeply nested comprehension. It also gives you a natural place to handle empty sequences, since min(a) raises an error when a is empty.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions