Pre-PEP: Unpacking in Comprehensions

FWIW this is clear to me. I would read the *x, y as re-packing the lists we’re iterating over and the *x for as unpacking the resulting lists. I suppose the confusion would be if someone imagines *x is a name in its own right and not an operation that considers whether the name is being read or written, but having used it in both contexts, it doesn’t strike me as confusing.

Given the existing one-liner alternatives:

[z for x in list_of_lists for z in x[:-1]]
[z for *x, _ in list_of_lists for z in x]

I think [*x for *x, _ in list_of_lists] is more readable. It even seems like a conveniently compact example to explain the difference between unpacking assignments and unpacking expressions[1].


  1. I’m not sure if we have terms for distinguishing these cases, but hopefully this is clear enough. ↩︎

7 Likes