Starred expressions raise SyntaxError
when used in list or generator comprehension.
I'm curious about the reason behind this; is it an implementation choice or there are technical constraints that would prevent this operation?
I've found a lot about the contexts that don't allow for unpacking iterables but nothing about why.
Example:
lis = [1, 2, 3, 4, 5]
listcomp = [*lis for i in range(3)]
I thought maybe I could use this to get [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
as a result, but it raises
SyntaxError("Iterable unpacking cannot be used in comprehension")
This was proposed in PEP 448 -- Additional Unpacking Generalizations but ultimately not accepted due to concerns about readability:
Earlier iterations of this PEP allowed unpacking operators inside list, set, and dictionary comprehensions as a flattening operator over iterables of containers: [...]
This was met with a mix of strong concerns about readability and mild support. In order not to disadvantage the less controversial aspects of the PEP, this was not accepted with the rest of the proposal.
Notably, the possibility to add this at a later point has not been ruled out.
This PEP does not include unpacking operators inside list, set and dictionary comprehensions although this has not been ruled out for future proposals.