Filter a list of strings and return a list with only your friend's name in it

Viewed 1502

I'm learning Python and trying to solve the same problem ("Friend or Foe?"). I wrote the code below and would like to find out how to move-on following "my logic" way.

It seems that it adds just the very first item to the new_friends list but doesn't iterate over all the elements of x list.

Beside above, the return value is None ... what am I not noticing here?

def friend(x):
    x = ["Ryan", "Kieran", "Jason", "Yous"]
    new_friends = []
    for str in x:
        if len(str) == 4:
            return new_friends.append(str)
    return new_friends[0:]

Instead of if statement I also tried a nested while loop .. but no success adding other items to the new_friends list.

1 Answers

Here's a fixed up version of your function that does what I believe you want:

def friend(x):
    new_friends = []
    for str in x:
        if len(str) == 4:
            new_friends.append(str) # no 'return' here
    return new_friends # return resulting list.  no need to return a slice of it

Here's a more concise version that uses a list comprehension:

def friend(candidates):
    return [candidate for candidate in candidates if len(candidate) == 4]

For either version of the function, this:

print(friend(["Ryan", "Kieran", "Jason", "Yous"]))

results in this:

['Ryan', 'Yous']
Related