2

The aim is to add two given lists through recursion. For example

[1,2,3] + [4,5,6] = [5,7,9]

I am getting an

int object is not iterable

error.

Here is the code:

def seqaddr(l1,l2):
    if len(l1)==1:
        l1[0]=l1[0]+l2[0]
        return l1
    else:
        return seqaddr(l1[:len(l1)-1],l2[:len(l2)-1]) + list(l1.pop()+l2.pop())

seqaddr([1,2,3],[4,5,6])
0

2 Answers 2

1

You can't convert an number to a list using list(n). You should use a list literal. Change the following line:

return seqaddr(l1[:len(l1)-1],l2[:len(l2)-1]) + list(l1.pop()+l2.pop())

to

return seqaddr(l1[:len(l1)-1],l2[:len(l2)-1]) + [l1.pop() + l2.pop()]

Update: Your function mutates the original arguments, which is generally considered a Bad Thing™. An idempotent version can be written as:

def seqaddr(l1, l2):
    if len(l1) == 1:
        return [l1[0] + l2[0]]
    else:
        return seqaddr(l1[:-1], l2[:-1]) + [l1[-1] + l2[-1]]
Sign up to request clarification or add additional context in comments.

1 Comment

@Codingbegginer Also see my update re: mutating arguments. Your function destroys l1 and l2, which may be unexpected by the consumer of your function.
0

A further simplification to the last line of code in the answer by Selcuk

def seqaddr(l1,l2):
if len(l1)==1:
    l1[0]=l1[0]+l2[0]
    return l1
else:
    return seqaddr(l1[:-1],l2[:-1]) + [l1.pop() + l2.pop()]

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.