Python3: on removing map, reduce, filter

beliavsky at aol.com beliavsky at aol.com
Mon Jan 10 01:20:38 CET 2005


Steve Holden wrote:
>>   def square(x):
>>       return x*x
>>   map(square, range(1000))

>> versus

>>   [x*x for x in range(1000)]

>> Hint: function calls are expensive.

>$ python -m timeit -s "def square(x): return x*x" "map(square,
range(1000))"
>1000 loops, best of 3: 693 usec per loop

>$ python -m timeit -s "[x*x for x in range(1000)]"
>10000000 loops, best of 3: 0.0505 usec per loop

Functions will often be complicated enought that inlining them is not
feasible. In Fortran 95 one can define an elemental function that takes
an argument of any shape (scalar, vector, matrix etc.) but of a
specified type, returning a result of the same shape, so that one could
write

elemental function square(i) result(isq)
integer, intent(in) :: i
integer               :: isq
isq = i*i
end function square

and then

print*,square((/i,i=0,999/))

The Numeric and Numarray Python modules have predefined ufunc's that
are essentially elemental functions with one or two arguments. It would
be nice if one could define new ufunc's using only Python code -- I
presume new ones can currently be added by writing C code.




More information about the Python-list mailing list