Python's "only one way to do it" philosophy isn't good?
Hrvoje Niksic
hniksic at xemacs.org
Fri Jun 29 06:57:24 EDT 2007
Douglas Alan <doug at alum.mit.edu> writes:
> I think you overstate your case. Lispers understand iteration
> interfaces perfectly well, but tend to prefer mapping fuctions to
> iteration because mapping functions are both easier to code (they
> are basically equivalent to coding generators) and efficient (like
> non-generator-implemented iterators). The downside is that they are
> not quite as flexible as iterators (which can be hard to code) and
> generators, which are slow.
Why do you think generators are any slower than hand-coded iterators?
Consider a trivial sequence iterator:
$ python -m timeit -s 'l=[1] * 100
class foo(object):
def __init__(self, l):
self.l = l
self.i = 0
def __iter__(self):
return self
def next(self):
self.i += 1
try:
return self.l[self.i - 1]
except IndexError:
raise StopIteration
' 'tuple(foo(l))'
10000 loops, best of 3: 173 usec per loop
The equivalent generator is not only easier to write, but also
considerably faster:
$ python -m timeit -s 'l=[1] * 100
def foo(l):
i = 0
while 1:
try:
yield l[i]
except IndexError:
break
i += 1
' 'tuple(foo(l))'
10000 loops, best of 3: 46 usec per loop
More information about the Python-list
mailing list