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

2

u/metaperl Oct 13 '14

is there a library providing something like what I'm trying to do, so that I don't waste my time?

Why did you write it and then ask?

This little library is targeted for people who think that x.filter(f).map(g) looks better than x = map(g, filter(f, x))

Well how about:

[g(y) for y in [x for x in coll if f(x)]]

Yes, I guess I like your dotted approach better. Easier to read from left to right for me.

4

u/bm371613 Oct 13 '14

The reason I wrote this prototype and then asked is that it only took me a few hours. These hours made it more clear to me what exactly am I going to do, and made it easier to ask if there is something like that already, since I have something to show.

7

u/Mecdemort Oct 13 '14

You could just do

[g(y) for y in x if f(y)]

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

u/bm371613 Oct 13 '14

Good idea, thanks

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

u/norwegianwood Oct 16 '14

You could try my asq package. It supports all the standard LINQ operators and is extensible too. Documentation is here and it's on PyPI. It works on Python 3 and Python 2.

-1

u/rhgrant10 Oct 13 '14

Thank you!