-1

Not sure where i went wrong, but it gives me [-1, [-2, [-3, []]]] instead of just [-1,-2,-3]

def search(list1,list2):
    if list2 == []:
        return list1
    elif list2[0] == list1[0]:
        return [-list1[0] , search(list1[1:],list2[1:])]

print search([1,2,3],[1,2,3])
Ruben Bermudez
  • 2,293
  • 14
  • 22

2 Answers2

2

I'm not entirely sure what goal your function is aimed at (why return the negative of a matching value?), but you can get your expected output by just concatenating lists in your return statement:

def search(list1,list2):
    if list2 == []:
        return list1
    elif list2[0] == list1[0]:
        return [-list1[0]] + search(list1[1:],list2[1:])

print search([1,2,3],[1,2,3])
# Output:
# [-1, -2, -3]
Marius
  • 58,213
  • 16
  • 107
  • 105
1

If you want to search for elements that are in the same position in both list and make a list with them but changing their sign, you don't need that, you can make it like:

A = [1,2,3]
B = [1,2,3]

print [ -i for i,j in zip(A,B) if i == j]
Ruben Bermudez
  • 2,293
  • 14
  • 22