r/Python • u/bm371613 • 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?
2
u/kankyo Oct 13 '14
One minor thing about naming: "next" and "step" are a bit confusing names, I guess they are the same as "take" and "drop" in functional languages? I think those names are better.
1
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]-1
2
u/metaperl Oct 13 '14
Why did you write it and then ask?
Well how about:
Yes, I guess I like your dotted approach better. Easier to read from left to right for me.