ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes

Chris Angelico rosuav at gmail.com
Thu Dec 13 02:14:08 CET 2012


On Thu, Dec 13, 2012 at 11:30 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Wed, 12 Dec 2012 17:20:53 -0500, Dave Cinege wrote:
>> To me for i in range(len(l)) seems like simpler, faster, tighter code
>> for this now.
>
> * the version with enumerate makes the intent more clear: since we
>   care about looping over the items, we should iterate over the
>   items directly, not over their indices;

To add to this: Using enumerate gives the possibility (don't know if
any current interpreter takes advantage or not, but a future one
certainly could) that the enumerate() call could be optimized out.
Yes, it's theoretically possible that someone could redefine
enumerate, which would be broken by such an optimization. But all it'd
take is some kind of directive-based optimization and voila, safe
performance improvements.

Example code used:
>>> def foo(x):
	for i,val in enumerate(x):
		print("x[%d] = %s"%(i,str(val)))

>>> def foo(x):
	for i in range(len(x)):
		val=x[i]
		print("x[%d] = %s"%(i,str(val)))

A simple look at dis.dis() for the above two functions disproves the
"faster". Steven has already disproven the "simpler" and "tighter".

(I would like, though, to see a key-providing iteration as a standard
feature. Looking at dis.dis() for the above examples and also at a
simple iteration over a dictionary's .items(), I'm seeing what looks
like a lot of effort to deal with the fact that iterators return a
stream of items, rather than a stream of keys and values. But it's
probably not worth changing now.)

ChrisA



More information about the Python-list mailing list