I was just messing around when I came across this quirk. And I wanted to make sure I am not crazy.

The following code (works in 2.x and 3.x):

from timeit import timeit
print ('gen: %s' % timeit('"-".join(str(n) for n in range(1000))', number=10000))
print ('list: %s' % timeit('"-".join([str(n) for n in range(1000)])', number=10000))

Doing 3 runs on each version, same machine.

note: I grouped the timings on the same line to save space here.

On my Python 2.7.5:

gen: 2.37875941643, 2.44095773486, 2.41718937347
list: 2.1132466183, 2.12248106441, 2.11737128131

On my Python 3.3.2:

gen: 3.8801268438439718, 3.9939604983350185, 4.166233972077624
list: 2.976764740845537, 3.0062614747229555, 3.0734980312273894

I wonder why this is.... Might it have something to do with how strings are implemented?


EDIT: I did it again without using range() since that has also changed slightly from 2.x to 3.x Instead I use the new code below:

from timeit import timeit
print ('gen: %s' % timeit('"-".join(str(n) for n in (1, 2, 3))', number=1000000))
print ('list: %s' % timeit('"-".join([str(n) for n in (1, 2, 3)])', number=1000000))

The Timing for Python 2.7.5:

gen: 2.13911803683, 2.16418448199, 2.13403650485
list: 0.797961223325,  0.767758578433, 0.803272800119

The Timing for Python 3.3.2:

gen: 2.8188347625218486, 2.882846655874985, 3.0317612259663718
list: 1.3590610502957934, 1.4878876089869366, 1.4978070529462615

EDIT2: It seems there were some more things throwing off the calculation, so I tried bringing it down to a bare-minimum.

New Code:

from timeit import timeit
print ('gen: %s' % timeit('"".join(n for n in ("1", "2", "3"))', number=1000000))
print ('list: %s' % 
Edit
Report