[Python-ideas] Fwd: Fwd: Fwd: unpacking generalisations for list comprehension
Nick Coghlan
ncoghlan at gmail.com
Tue Oct 18 02:31:25 EDT 2016
On 18 October 2016 at 13:32, David Mertz <mertz at gnosis.cx> wrote:
> On Mon, Oct 17, 2016 at 7:50 PM, Random832 <random832 at fastmail.com> wrote:
>> I feel like I should be honest about something else - I'm always a
>> little bit confused by the ordering for comprehensions involving
>> multiple clauses.
>
> Me too! I get the order of nested loops in comprehensions wrong about 25% of
> the time. Then it's a NameError, and I fix it.
>
> This is a lot of why I like a utility function like `flatten()` that is
> pretty much self-documenting. Perhaps a couple other itertools helpers
> would be nice.
This is also one of the main reasons that named generator expression
pipelines can sometimes be easier to read than nested comprehensions:
incrementally_increasing_ranges = (range(end) for end in itertools.count())
flatten = itertools.chain.from_iterable
incrementally_increasing_cycles = flatten(incrementally_increasing_ranges())
Forcing ourselves to come up with a name for the series of values
produced by the outer iteration then makes that name available as
documentation of our intent for future readers of the code.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list