Home > Blockchain >  Why does a for loop return only the first item when a list comprehension returns everything?
Why does a for loop return only the first item when a list comprehension returns everything?

Time:11-02

trying to use zip() to combine words together but wondering why the below codes lead to different results?

1)

def concatenate(L1,L2,connector):
    for (word1,word2) in zip(L1,L2):
        return [word1 connector word2]

concatenate(['A','B'],['a','b'],'-')

expecting ['A-a','B-b'] but I got: ['A-a'] only

2)

def concatenate(L1,L2,connector):
    return [word1 connector word2 for (word1,word2) in zip(L1,L2)]

I got: ['A-a', 'B-b']

CodePudding user response:

return exits the function. If you want to return multiple values, you could use yield, though it might be overkill for your purposes:

def concatenate(L1, L2, connector):
    for word1, word2 in zip(L1, L2):
        yield word1 connector word2

list(concatenate(['A','B'], ['a','b'], '-'))  # -> ['A-a', 'B-b']

Note that you need to add list() on the function call to actually get a list out.

CodePudding user response:

I will try answer this question. The code just returning first iteration.

def concatenate(L1,L2,connector):
    merge=[]
    for (word1,word2) in zip(L1,L2):
        merge=merge [word1 connector word2]
    return(merge)

print(concatenate(['A','B'],['a','b'],'-'))

and this code will run all iteration

def concatenate(L1,L2,connector):
    return [word1 connector word2 for (word1,word2) in zip(L1,L2)]
    

print(concatenate(['A','B'],['a','b'],'-'))

In first code, i just add the last string in some array and returning the variable

  • Related