Reputation: 43
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
Reputation: 8685
As soon as i
is in l
your code return
s, 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
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
Reputation: 622
try this:
def f(w,l):
common = []
for i in w:
if i in l:
common.append(i)
return common
Upvotes: 0