Python prints an incomplete list of a summation of two lists
Question:
I’m trying to calculate (and print) the summation of two lists, given in the code below
def a(list1, list2):
rv = []
for i in range(len(list1)):
rv.append(list1[i] + list2[i])
return rv
list1 = [1, 2]
list2 = [3, 4]
d = a(list1, list2)
print('rv =', d)
but the above print function only prints
rv = [4]
which is only the zeroth entry of rv
, I was expecting it to print rv = [4, 6]
Any suggestions?
Answers:
return rv
must be de-indented out of the for loop, otherwise it will exit the function in the first iteration:
def a(list1, list2):
rv = []
for i in range(len(list1)):
rv.append(list1[i] + list2[i])
return rv
P.S. – your code can be simplified using zip
and a list comprehension:
def a(list1, list2):
return [a + b for a, b in zip(list1, list2)]
I’m trying to calculate (and print) the summation of two lists, given in the code below
def a(list1, list2):
rv = []
for i in range(len(list1)):
rv.append(list1[i] + list2[i])
return rv
list1 = [1, 2]
list2 = [3, 4]
d = a(list1, list2)
print('rv =', d)
but the above print function only prints
rv = [4]
which is only the zeroth entry of rv
, I was expecting it to print rv = [4, 6]
Any suggestions?
return rv
must be de-indented out of the for loop, otherwise it will exit the function in the first iteration:
def a(list1, list2):
rv = []
for i in range(len(list1)):
rv.append(list1[i] + list2[i])
return rv
P.S. – your code can be simplified using zip
and a list comprehension:
def a(list1, list2):
return [a + b for a, b in zip(list1, list2)]