0

whenever I run following code of adding two lists in python below mentioned error appears

    def add_lists(L1, L2):
        R = []
        for i in range(0, len(L1)):
            R.append(L1[i]+L2[i])
        return R

    L2 = [3, 3, 3, 3]
    L1 = [1, 2, 3, 4]
    add_lists(L1, L2)
    print("Resultant list of: ", str(L1), '& ' + str(L2), 'is', R)

this code yields NameError: name 'R' is not defined

1
  • The variable name R is defined within your function, but not outside it: that's why you see this error. You should call your function and assign the result to a variable. Say res = add_lists(L1, L2). Then you can use res in your print statement. Commented Jul 24, 2022 at 9:23

3 Answers 3

1

The variable R is local to your function and so is not accessible to your print statement. (Generally, this is good! It makes the function self-contained and avoids dependencies on what global variables may or may not exist.)

To print the result of the function, assign the result to an in-scope variable and use that.

def add_lists(L1, L2):
    R = []
    for i in range(0, len(L1)):
        R.append(L1[i]+L2[i])
    return R

L2 = [3, 3, 3, 3]
L1 = [1, 2, 3, 4]
res = add_lists(L1, L2)  # assigns the result of the function call to a variable we can access
print("Resultant list of: ", str(L1), '& ' + str(L2), 'is', res)
Sign up to request clarification or add additional context in comments.

2 Comments

It better to use zip to get two number from lists and add together, no need to use index...
Indeed. Beyond OP's specific problem there are a few ways the code could be cleaned up.
0

You defined R in a local scope "it looks like inside a function" while you are trying to use it outside of that scope in the last line.

Try moving the initialization of "R = []" to the outer scope.

Comments

0

its because R = [] is inside the function and print is outside the function... so try this :

R = []
def add_lists(L1, L2):
        
        for i in range(0, len(L1)):
            R.append(L1[i]+L2[i])
        return R

L2 = [3, 3, 3, 3]
L1 = [1, 2, 3, 4]
add_lists(L1, L2)
print("Resultant list of: ", str(L1), '& ' + str(L2), 'is', R)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.