[Tutor] str.split and quotes

Kent Johnson kent37 at tds.net
Sat Apr 9 13:45:27 CEST 2005


smiles at saysomething.com wrote:
> I was glad to see your post showing how to run a list of functions 
> through the timer.  That's a nice way to do it!  You better slip some 
> square brackets into your definition of d though:
> 
>  
> 
>     d = dict( [((i,i,i), i) for i in range(1000)])

In Python 2.4 they are not needed. For earlier versions, you are right. (((i,i,i), i) for i in 
range(1000)) is a generator expression. It's value is a generator object that supports the iterator 
protocol.

  >>> g=(((i,i,i), i) for i in range(1000))
  >>> g
<generator object at 0x008D7198>
  >>> g.next()
((0, 0, 0), 0)
  >>> g.next()
((1, 1, 1), 1)

In general, if you replace the [] of a list comprehensions with () you will get a generator 
comprehension. The () are required but syntactically they can be part of the function call syntax - 
you don't have to add another () if one is present.

BTW a note about timing for optimization - it is important to do your timing on the same Python 
version that you will deploy with; there have been significant speedups in portions of Python 2.4 
and 2.3. For example list comprehension has gotten much faster.

Kent



More information about the Tutor mailing list