1
def intersect(seq,seq1):
    res = []
    for x in seq:
        if x in seq1:
            res.append(x)
            return res

return res only returns ['s'] but with seq="spam" and seq1="scam" in the function call, why is it not returning ['s','a','m']?

wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

3

Because the line

return res

is not in the correct position (in other words, it has bad indentation). It should be outside the for loop, so your program first finishes the loop and then returns the result:

def intersect(seq, seq1):
    res = []
    for x in seq:
        if x in seq1:
            res.append(x)
    return res

Note: Remember that indentation is extremely important in Python, because it's used to determine the grouping of statements.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
1

Your return res indentation is wrong. It should be:

def intersect(seq,seq1):
    res=[]
    for x in seq:
        if x in seq1:
            res.append(x)
    return res

>>> intersect('scam','spam')
['s','a','m']

What you were doing earlier was that you were appending one value and then returning it. You want to return res when you have appended all your values. This happens after the for loop and that is when you put the return res line. Therefore, it should have the same indentation as the for statement.

sshashank124
  • 31,495
  • 9
  • 67
  • 76