RFC: For Loop Invariants
Terry Reedy
tjreedy at udel.edu
Sat Apr 11 00:35:35 EDT 2020
On 4/10/2020 4:44 PM, Elliott Dehnbostel wrote:
> chars = "abcaaabkjzhbjacvb"
> seek = {'a','b','c'}
> count = 0for a in chars:
> if a in seek:
> count += 1
Why did you repeatly omit the \n after 0? Please paste code that ran
> Gross. Twice nested for a simple count.
Twice indented does not particularly bother me.
> [snip]
> *We could do this:*
>
> chars = "abcaaabkjzhbjacvb"
> seek = {'a','b','c'}
> count = sum([1 for a in chars if a in seek])
>
> However, this changes important semantics by creating an entire new
> list before summing.
Unnecessary. Use a generator comprehension (expression).
sum(1 for a in chars if a in seek)
> chars = "abcaaabkjzhbjacvb"
> seek = {'a','b','c'}
> count = 0 # fixed
> for a in chars if a in seek: count += 1
Rejected and rejected again, any mixing of keyword clauses like this
except in comprehensions. The sum expression is shorter and only 1 line.
--
Terry Jan Reedy
More information about the Python-list
mailing list