correct style for element-wise operations on lists without numpy (python) -


i operate on lists element element without using numpy, example, want add([1,2,3], [2,3,4]) = [3,5,7] , mult([1,1,1],[9,9,9]) = [9,9,9], i'm not sure way of doing considered 'correct' style.

the 2 solutions came were

def add(list1,list2):     list3 = []     x in xrange(0,len(list1)):         list3.append(list1[x]+list2[x])     return list3  def mult(list1, list2):     list3 = []     x in xrange(0,len(list1)):         list3.append(list1[x]*list2[x])     return list3  def div(list1, list2):     list3 = []     x in xrange(0,len(list1)):         list3.append(list1[x]/list2[x])     return list3  def sub(list1, list2):     list3 = []     x in xrange(0,len(list1)):         list3.append(list1[x]-list2[x])     return list3 

where each operator given separate function

and

def add(a,b)     return a+b def mult(a,b)     return a*b def div(a,b)     return a/b def sub(a,b)     return a-b def elementwiseoperation(list1, list2, function):     list3 = []     x in xrange(0,len(list1)):         list3.append(function(list1[x],list2[x]))     return list3 

where basic functions defined, , have separate function use them on each element. skimmed through pep8, didn't find directly relevant. way better?

the normal way use map or itertools.imap:

import operator multiadd = lambda a,b: map(operator.add, a,b) print multiadd([1,2,3], [2,3,4]) #=> [3, 5, 7] 

ideone: http://ideone.com/yrlhxw

map c-implemented version of elementwiseoperation, advantage of having standard name, working iterable type , being faster.

alternatively, use partial , map pleasingly pointfree style:

import operator import functools  multiadd = functools.partial(map, operator.add) print multiadd([1,2,3], [2,3,4]) #=> [3, 5, 7] 

ideone: http://ideone.com/buhrcw

anyway, you've taken first steps in functional programming yourself. suggest read around topic.

as general matter of style, iterating index using range considered wrong thing, if want visit every item. usual way of doing iterate structure directly. use zip or itertools.izip iterate in parallel:

for x in l:     print l  a,b in zip(l,k):     print a+b 

and usual way iterate create list not use append, list comprehension:

[a+b a,b in itertools.izip(l,k)] 

Comments