简体   繁体   中英

Why is it not possible to unpack lists inside a list comprehension?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM