[Python-ideas] Fwd: Fwd: unpacking generalisations for list comprehension
Martti Kühne
mar77i at mar77i.ch
Thu Oct 13 10:34:49 EDT 2016
On Wed, Oct 12, 2016 at 5:41 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> However, set builder notation doesn't inherently include the notion of
> flattening lists-of-lists. Instead, that's a *consumption* operation
> that happens externally after the initial list-of-lists has been
> built, and that's exactly how it's currently spelled in Python:
> "itertools.chain.from_iterable(subiter for subiter in iterable)".
On Wed, Oct 12, 2016 at 5:42 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> The fundamental design principle of list comps is that they are
> equivalent to a for-loop with a single append per loop:
>
> [expr for t in iterable]
>
> is equivalent to:
>
> result = []
> for t in iterable:
> result.append(expr)
>
>
> If I had seen a list comprehension with an unpacked loop variable:
>
> [t for t in [(1, 'a'), (2, 'b'), (3, 'c')]]
>
>
As it happens, python does have an external consumption operation that
happens externally with an iteration implied:
for t in iterable:
yield t
For your example [t for t in [(1, 'a'), (2, 'b'), (3, 'c')]] that would mean:
for t in [(1, 'a'), (2, 'b'), (3, 'c')]:
yield t
And accordingly, for the latter case [*t for t in [(1, 'a'), (2, 'b'),
(3, 'c')]] it would be:
for item in [(1, 'a'), (2, 'b'), (3, 'c')]:
for t in item:
yield t
cheers!
mar77i
More information about the Python-ideas
mailing list