Python3: on removing map, reduce, filter
John Machin
sjmachin at lexicon.net
Sun Jan 9 18:43:15 EST 2005
Steven Bethard wrote:
> Note that list comprehensions are also C-implemented, AFAIK.
Rather strange meaning attached to "C-implemented". The implementation
generates the code that would have been generated had you written out
the loop yourself, with a speed boost (compared with the fastest DIY
approach) from using a special-purpose opcode LIST_APPEND. See below.
>>> def afunc(n):
... return [x*x for x in xrange(n)]
...
>>> afunc(3)
[0, 1, 4]
>>> import dis
>>> dis.dis(afunc)
2 0 BUILD_LIST 0
3 DUP_TOP
4 STORE_FAST 1 (_[1])
7 LOAD_GLOBAL 1 (xrange)
10 LOAD_FAST 0 (n)
13 CALL_FUNCTION 1
16 GET_ITER
>> 17 FOR_ITER 17 (to 37)
20 STORE_FAST 2 (x)
23 LOAD_FAST 1 (_[1])
26 LOAD_FAST 2 (x)
29 LOAD_FAST 2 (x)
32 BINARY_MULTIPLY
33 LIST_APPEND
34 JUMP_ABSOLUTE 17
>> 37 DELETE_FAST 1 (_[1])
40 RETURN_VALUE
>>> def bfunc(n):
... blist=[]; blapp=blist.append
... for x in xrange(n):
... blapp(x*x)
... return blist
...
>>> bfunc(3)
[0, 1, 4]
>>> dis.dis(bfunc)
2 0 BUILD_LIST 0
3 STORE_FAST 3 (blist)
6 LOAD_FAST 3 (blist)
9 LOAD_ATTR 1 (append)
12 STORE_FAST 2 (blapp)
3 15 SETUP_LOOP 34 (to 52)
18 LOAD_GLOBAL 3 (xrange)
21 LOAD_FAST 0 (n)
24 CALL_FUNCTION 1
27 GET_ITER
>> 28 FOR_ITER 20 (to 51)
31 STORE_FAST 1 (x)
4 34 LOAD_FAST 2 (blapp)
37 LOAD_FAST 1 (x)
40 LOAD_FAST 1 (x)
43 BINARY_MULTIPLY
44 CALL_FUNCTION 1
47 POP_TOP
48 JUMP_ABSOLUTE 28
>> 51 POP_BLOCK
5 >> 52 LOAD_FAST 3 (blist)
55 RETURN_VALUE
>>>
More information about the Python-list
mailing list