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?
How do I conditionally unpack items in a Python comprehension?
Answers
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].
Reply to this answer
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
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
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.
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.