Codingbeginner
Codingbeginner

Reputation: 57

int object is not iterable adding two lists

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])

Upvotes: 2

Views: 83

Answers (2)

Selcuk
Selcuk

Reputation: 59184

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]]

Upvotes: 1

Faizan
Faizan

Reputation: 1

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()]

Upvotes: 0

Related Questions