Skip to content

Instantly share code, notes, and snippets.

@tadasv
Created April 25, 2013 18:00
Show Gist options
  • Save tadasv/5461753 to your computer and use it in GitHub Desktop.
Save tadasv/5461753 to your computer and use it in GitHub Desktop.
generators vs lists
[] tadas@tadascb-2 ~/tmp: cat generators.py
def munge(i):
return i ** 2 + i
def func1():
return ( munge(i) for i in xrange(10) )
def func2():
return [ munge(i) for i in xrange(10) ]
if __name__ == '__main__':
print list(func1())
print func2()
[] tadas@tadascb-2 ~/tmp: python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> import generators
>>> dis.dis(generators.func1)
5 0 LOAD_CONST 1 (<code object <genexpr> at 0x109edb3b0, file "generators.py", line 5>)
3 MAKE_FUNCTION 0
6 LOAD_GLOBAL 0 (xrange)
9 LOAD_CONST 2 (10)
12 CALL_FUNCTION 1
15 GET_ITER
16 CALL_FUNCTION 1
19 RETURN_VALUE
>>> dis.dis(generators.func2)
8 0 BUILD_LIST 0
3 LOAD_GLOBAL 0 (xrange)
6 LOAD_CONST 1 (10)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 18 (to 34)
16 STORE_FAST 0 (i)
19 LOAD_GLOBAL 1 (munge)
22 LOAD_FAST 0 (i)
25 CALL_FUNCTION 1
28 LIST_APPEND 2
31 JUMP_ABSOLUTE 13
>> 34 RETURN_VALUE
>>> from timeit import Timer
>>> t1 = Timer(generators.func1)
>>> t2 = Timer(generators.func2)
>>> t1.timeit()
0.8525791168212891
>>> t2.timeit()
3.2556989192962646
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment