substituting list comprehensions for map()

Neil Crighton neilcrighton at gmail.com
Mon Nov 2 10:24:13 CET 2009


Steven D'Aprano <steven <at> REMOVE.THIS.cybersource.com.au> writes:

> > 
> > operandlist1=[1,2,3,4,5]
> > operandlist2=[5,4,3,2,1]
> > 
> > and resultlist will become [6,6,6,6,6].  Using map(), I can do:
> > 
> > map(lambda op1,op2: op1 + op2, operandlist1, operandlist2)
> 
> If the two lists are very large, it would be faster to use this:
> 

If the two lists are *very* large and every element in each list has the same
type, you should use NumPy arrays (http://numpy.scipy.org/).

>>> import numpy
>>> operandlist1 = numpy.array([1, 2, 3, 4, 5])
>>> operandlist2 = numpy.array([5, 4, 3, 2, 1])
>>> resultlist = operandlist1 + operandlist2
>>> resultlist
array([6, 6, 6, 6, 6])


Neil





More information about the Python-list mailing list