python's 'return' returns only first iteration result of the loop

前端 未结 2 572
-上瘾入骨i
-上瘾入骨i 2021-01-16 04:26
def intersect(seq,seq1):
    res = []
    for x in seq:
        if x in seq1:
            res.append(x)
            return res

return res only retu

2条回答
  •  春和景丽
    2021-01-16 05:10

    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.

提交回复
热议问题