I would like to operate on lists element by element without using numpy, for example, i want add([1,2,3], [2,3,4]) = [3,5,7]
and mult([1,1,1],[9,9,9]) = [9,9,9]
, but i'm not sure which way of doing is it considered 'correct' style.
The two solutions i came up with were
def add(list1,list2):
list3 = []
for x in xrange(0,len(list1)):
list3.append(list1[x]+list2[x])
return list3
def mult(list1, list2):
list3 = []
for x in xrange(0,len(list1)):
list3.append(list1[x]*list2[x])
return list3
def div(list1, list2):
list3 = []
for x in xrange(0,len(list1)):
list3.append(list1[x]/list2[x])
return list3
def sub(list1, list2):
list3 = []
for x in xrange(0,len(list1)):
list3.append(list1[x]-list2[x])
return list3
where each operator is given a 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 = []
for x in xrange(0,len(list1)):
list3.append(function(list1[x],list2[x]))
return list3
where all the basic functions are defined, and I have a separate function to use them on each element. I skimmed through PEP8, but didn't find anything directly relevant. Which way is better?