RFC: For Loop Invariants
Rhodri James
rhodri at kynesim.co.uk
Sat Apr 11 06:43:33 EDT 2020
On 10/04/2020 21:44, Elliott Dehnbostel wrote:
> Hello Everyone,
>
> I've also posted this to the python-ideas mailing list, but I thought to
> post here as well for a more general audience.
>
> If I've done this incorrectly, please let me know so that I can
> improve/revise. I'm new to the Python community and quite enjoy the more
> functional features of Python 3, but have I have a peeve about it. I'd like
> to propose and discuss the following enhancement to Python 3:
>
> *Consider the following trivial for-loop:*
>
> chars = "abcaaabkjzhbjacvb"
> seek = {'a','b','c'}
> count = 0for a in chars:
> if a in seek:
> count += 1
>
> Gross. Twice nested for a simple count.
a) I don't personally think that's gross (apart from the missing
newline, which is just an email artefact I assume).
b) If it's simple like this and you care enough, refactor it as a
comprehension:
count = sum(1 for a in chars if a in seek)
It it's not so simple, neither the comprehension nor your proposal are
going to be as readable as the twice nesting.
--
Rhodri James *-* Kynesim Ltd
More information about the Python-list
mailing list