Skip to content

Improve ilen() clarity and speed. #894

@rhettinger

Description

@rhettinger

Stefan Pochmann came up with this new way to write ilen():

from itertools import compress, repeat

def ilen(iterable):
    return sum(compress(repeat(1), zip(iterable)))

Besides being shorter and faster, it is more readable with a point-free functional style that doesn't rely on side-effects. The only "trick" is using zip() to wrap the input with 1-tuples which compress() reads as true values. It is rather creative, yet each function call is being used in a canonical way.

Over a dozen other ideas were kicked around (some even a little faster), but none of the fastest were as clear and straight-forward as this one. Also, this variant is likely to be the most stable across different builds on Python (everything that makes it fast has long been stable and is unlikely to change during the current flurry of interpreter evolution). Code like this really shows off what can be done with an "iterator algebra" that composes existing fast, memory friendly tools to make something new.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions