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

前端 未结 2 563
-上瘾入骨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:01

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题