r/Python • • Oct 13 '14

Python: rich iterator

I could not find a library to fit my needs, so I decided to write one.. (standard story)

Just in case I'm not good at searching: is there a library providing something like what I'm trying to do, so that I don't waste my time?

1 Upvotes

8 comments sorted by

View all comments

5

u/benhoyt PEP 471 Oct 13 '14

Please, Python != Lisp. :-) I fully agree with Guido here. Python has beautiful built-in tools to do filter and map: list comprehensions and generator expressions. For example:

>>> numbers = [2, 7, 4, 1, 9, 3, 8, 5, 2, 8]
>>> result = [n*10 for n in numbers if n % 2]
>>> result
[70, 10, 90, 30, 50]
>>> result[:3]
[70, 10, 90]

Or, if you're dealing with large lists and want to keep them iterators, use generator expressions and the stdlib's itertools.islice:

>>> result = (n*10 for n in numbers if n % 2)
>>> sliced = islice(it, 3)
>>> sliced
<itertools.islice object at 0x00000000020E2CC8>
>>> list(sliced)
[70, 10, 90]