Home > OS >  int object is not iterable adding two lists
int object is not iterable adding two lists

Time:10-28

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

CodePudding user response:

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

CodePudding user response:

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