0

I am writing code about two lists and the sum element without using the sum function. So I need to return the sum of its elements. How do I define a list c with the total number of list a and b

The code below is what I already tried.

def add(list_a, list_b):
    list_a = [1, 2, 3, 4, 5]
    list_b = [1, 2, 3, 4, 5]
    list_c = []

for i in range (0,5):
    list_c.append(list_a[i]+second[i])

print (list_c)

The error code:

File "sum.py", line 7, in

list_c.append(list_a[i]+second[i])

NameError: name 'list_c' is not defined

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
Aka
  • 19
  • 2

3 Answers3

1

You have an indentation problem. It should work if you indent the for block and the print statement. You also have a typo, second[i] should be list_b[i].

def add(list_a, list_b): 
    list_c = [] 

    for i in range(0,5): 
        list_c.append(list_a[i]+list_b[i]) 

    return(list_c)

list_a = [1, 2, 3, 4, 5] 
list_b = [1, 2, 3, 4, 5]

print(add(list_a, list_b))
# [2, 4, 6, 8, 10]

A really short way to write this would be:

print([x+y for x,y in zip(list_a, list_b)])

It only works when the lists have the same length.

André Laszlo
  • 15,169
  • 3
  • 63
  • 81
  • @roganjosh I don't know. It's the `add` function OP tried to declare. I might have gotten the question wrong though. – André Laszlo Jun 16 '19 at 17:14
  • The `add` function doesn't make sense here, the parameters are immediately overwritten so serves no purpose. – Peter Featherstone Jun 16 '19 at 17:16
  • @PeterFeatherstone yeah that's also a problem. I think they meant to declare it outside the function. Did a copy-paste and forgot to move it :) Fixed, thanks for the feedback. – André Laszlo Jun 16 '19 at 17:18
1

There are two issues. First, you don't need to define your lists inside a function, and secondly you were referencing the second list as second instead of list_b. The below is all you need:

list_a = [1, 2, 3, 4, 5]
list_b = [1, 2, 3, 4, 5]
list_c = []

for i in range(0, 5):
    list_c.append(list_a[i] + list_b[i])

print (list_c)

Alternatively if you want to use it as a reusable function then you can move your loop logic into the function itself and pass the lists as parameters:

def add(list_a, list_b): 
    summed_list = [] 

    for i in range(0, 5): 
        summed_list.append(list_a[i] + list_b[i]) 

    return summed_list

summed = add([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
print(summed)
Peter Featherstone
  • 7,835
  • 4
  • 32
  • 64
0

You might use map in order to achieve that following way:

list_a = [1, 2, 3, 4, 5]
list_b = [1, 2, 3, 4, 5]
def add(a,b):
    return list(map(lambda x,y:x+y,list_a,list_b))
print(add(list_a,list_b))

Output:

[2, 4, 6, 8, 10]
Daweo
  • 31,313
  • 3
  • 12
  • 25