~/Blog

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Quick Python: Length of Iterables

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

I wanted to find the length of what I know is a finite iterable. Normally you would think of using the len function but it does not work in this case. Al Hoo on StackOverflow shared a quick snippet to calculate this.

from functools import reduce

def ilen(iterable):
    return reduce(lambda sum, element: sum + 1, iterable, 0)

This also turns out to be memory efficient since we are only loading in one object into memory from the iterable at a time.

Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter

Published a response to this? :