RFC: For Loop Invariants

Tony Flury tony.flury at btinternet.com
Mon Apr 20 07:08:03 EDT 2020


On 10/04/2020 21:44, Elliott Dehnbostel wrote:
> *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.

Creating the list is pointless in this case - sum will take any 
iterable, including a generator expression:

chars = "abcaaabkjzhbjacvb"
seek = {'a','b','c'}
count = sum(1 for a in chars if a in seek)

So you haven't really changed any semantics - and it seems that this is 
far better than fiddling with the for loop syntax.


More information about the Python-list mailing list