Kerry C
Kerry C

Reputation: 43

Why am I only getting one item from list

I am trying to get shared letters from a string compared to a list of letters. I only return the last letter of l that shares with w . I want all the shared letters instead.

def f(w,l):
    common = []
    for i in w:
        if in i in l:
            return common.append(i)

Upvotes: 2

Views: 93

Answers (3)

jramirez
jramirez

Reputation: 8685

As soon as i is in l your code returns, which immediately exits your function. instead do this:

def f(w,l):
    common = []
    for i in w:
        if i in l:
            common.append(i) # no return needed so it will collect all
    return common

Make sure you return common at the end your function so you get all the values stored in common.

Upvotes: 6

SethMMorton
SethMMorton

Reputation: 48745

The problem is that the .append method of a list returns None. You were returning from the function the first time you did .append, so you were always going to return None from the function.

I think that what you are really looking for is a list comprehension:

def f(w,l):
    return [i for i in w if i in l]

As others have pointed out, you might want to choose more descriptive variable names.

Upvotes: 0

Garth5689
Garth5689

Reputation: 622

try this:

def f(w,l):
    common = []
    for i in w:
        if i in l:
            common.append(i)

    return common

Upvotes: 0

Related Questions