On Mon, Mar 16, 2015 at 3:01 AM, Frank Millman <fr...@chagford.com> wrote: > C:\>python -m timeit -s "x = range(65, 91); y = (chr(z) for z in x)" > "dict(zip(x, y))" > 100000 loops, best of 3: 11.9 usec per loop > > C:\>python -m timeit -s "x = range(65, 91); y = (chr(z) for z in x)" "{a: b > for a, b in zip(x, y)}" > 100000 loops, best of 3: 7.24 usec per loop
Since the setup code is only run once, the generator expression used for y is only iterated over once. On every subsequent loop, zip is producing an empty result. So this measurement is really just capturing the overhead of the dict construction. Compare: $ python3 -m timeit -s "x = range(65, 91); y = (chr(z) for z in x)" "dict(zip(x,y))" 1000000 loops, best of 3: 0.9 usec per loop $ python3 -m timeit -s "x = range(65, 91); y = [chr(z) for z in x]" "dict(zip(x,y))" 100000 loops, best of 3: 2.69 usec per loop $ python3 -m timeit -s "x = range(65, 91); y = (chr(z) for z in x)" "{a:b for a,b in zip(x,y)}" 1000000 loops, best of 3: 0.837 usec per loop $ python3 -m timeit -s "x = range(65, 91); y = [chr(z) for z in x]" "{a:b for a,b in zip(x,y)}" 100000 loops, best of 3: 2.67 usec per loop -- https://mail.python.org/mailman/listinfo/python-list