-2

Why is the 'else' part marked in red when I try to run it? It says 'invalid syntax'.

def interseccion(lista, lista2, resultado=[]):
if lista != []:
    if lista[0] in lista2:
        return interseccion(lista[1:], lista2, resultado+[lista[0]]
    else:                 
        return interseccion(lista[1:], lista2, resultado]

return resultado
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user2833752
  • 11
  • 1
  • 2
  • 3
    Your opening parenthesis - '(' has no closing parenthesis ')'... maybe other problems too. – davecom Oct 10 '13 at 02:44
  • 4
    [Mutable default arguments can cause troubles.](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument) – Ashwini Chaudhary Oct 10 '13 at 02:44
  • 1
    Aside: the idea of the question title is to summarize the question in a way which will be useful to other people who might be looking to help or looking for an answer to the same question. "Why I'm getting this error? Im a noobie" isn't very likely to be. – DSM Oct 10 '13 at 02:49

2 Answers2

2

The specific error is due to a missing close parenthesis:

    return interseccion(lista[1:], lista2, resultado+[lista[0]] ) <-- that parenthesis is needed
SheetJS
  • 22,470
  • 12
  • 65
  • 75
  • And similarly in the second call to `interseccion()` (or, I suppose I should write `interseccion(`) — though there's a difference; there's a stray `]` there in lieu of the `)`. – Jonathan Leffler Oct 10 '13 at 02:48
  • @JonathanLeffler you are correct, but the question specifically asked about the error surrounding the `else`. – SheetJS Oct 10 '13 at 02:49
  • @user2833752 in general, when you have a syntax error, you should look before the identified part to find the issue – SheetJS Oct 10 '13 at 02:53
0

You have to close your parentheses in both of your return statements:

return interseccion(lista[1:], lista2, resultado+[lista[0]])

and

return interseccion(lista[1:], lista2, resultado)

Also if lista != []: is more idiomatically written simply as if lista:.

And I'm not quite sure if you want resultado to be an empty list by default! Maybe the default value should be None instead and then you can specify:

if resultado is None:
    resultado = []

at the beginning.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Shashank
  • 13,713
  • 5
  • 37
  • 63