On Fri, Apr 10, 2020 at 4:27 PM Elliott Dehnbostel <pydehnbostel@gmail.com> wrote:
Consider the following trivial for-loop:
chars = "abcaaabkjzhbjacvb"
seek = {'a','b','c'}
count = 0
for a in chars:
     if a in seek:
          count += 1

I would definitely not write it that way.  Instead I would write:

for a in chars:
    count += a in seek

Or quite likely simply:

count = sum(a in seek for a in chars)

Now your trivial example is ... well, trivial.  Often we  want to do different things if the membership is or isn't satisfied.  Sometimes we can simplify like this:

stuff = [this if a in seek else that for a in chars]
count = sum([1 for a in chars if a in seek])
This is kinda-sorta going in the right direction, but it has a bunch of noise for no reason.  Booleans subclass ints, with True being a kind of 1 and False being a kind of 0.  We don't need to restate that in the comprehension.  Also no need to build a separate if when you've already stated the condition. Also, sum is perfectly happy (and ever so slightly faster) dealing with a generator comprehension.

Neither the inline if nor your proposal deal with actual blocks:

for a in chars:
    if a in seek:
        do_this(a)
        and_that(a)
    else:
        other_stuff(a)
        still_more(a)

But neither do we actually need any shorter way to spell that, which is already clear.

--
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.