website/content/blog/pyleniterables.md

18 lines
644 B
Markdown
Raw Normal View History

2020-03-29 00:35:21 -04:00
---
title: "Quick Python: Length of Iterables"
date: 2020-03-25T18:28:09-04:00
draft: false
2022-01-02 14:24:29 -05:00
tags: ["Python"]
2023-01-05 14:04:45 -05:00
medium_enabled: true
2020-03-29 00:35:21 -04:00
---
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](https://stackoverflow.com/a/44351664) on StackOverflow shared a quick snippet to calculate this.
```python
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.