iterators (was: python-dev summary)

Jeff Petkau jpet at eskimo.com
Sat Feb 17 07:11:12 CET 2001


Steve Purcell <stephen_purcell at yahoo.com> wrote in message
news:mailman.982313491.5504.python-list at python.org...
> This new proposal sounds 'neat', but just think about plugging the new
> iterator syntax into list comprehensions like the following (stolen from
the
> PEP):
>
> >>> nums = [1,2,3,4]
> >>> fruit = ["Apples", "Peaches", "Pears", "Bananas"]
> >>> print [(i,f) for i in nums for f in fruit if f[0] == "P" if i%2 == 1]
> [(1, 'Peaches'), (1, 'Pears'), (3, 'Peaches'), (3, 'Pears')]
>
> Sprinkle a few ':' iterator magic symbols in there, and it doesn't look
like
> Python any more. Of course, if the intention is to win over the Perl
> community...
>
> -Steve

I totally agree with this. I hope future language additions
take the form of builtin functions like zip() instead of new
syntax.

Functions are more in line with the 'explicit is better than
implicit' argument--does 'for x in dict' iterate over keys,
values, or items? What better way could we specify this than
keys(), values(), and items()?

For iterating through lists with indices, we could just toss
something like this into __builtins__:

    def indexed(x):
        """returns a list of (index,value) pairs
        for the mapping or sequence x."""

        if hasattr(x,'items'):
            return x.items()
        else:
            return zip(range(len(x)),x)

    for i,v in indexed([1,2,3]):
        print 'elem at',i,'is',v

The only argument I've seen for new syntax is efficiency--
dict.keys() et al can be expensive for big dictionaries.
But this is solved very nicely the way xrange() and
xreadlines() did it, with lazy iterators. Maybe Guido thinks
they're a hack, but they're a simple, efficient, consistent,
easy to use solution to a recurring problem.  We could use
more hacks like that!

Admittedly the xfoo() naming convention is ugly, but that's
the nature of backwards compatibility. New iterators could
be lazy by default, and if you want an actual list, just use
list(x).

Um, what topic did I start with again?

Oh, yeah. And function names are much easier to look up in the
documentation.

--Jeff






More information about the Python-list mailing list