01-3: Friend or Foe?

Python, Filter, Anonymous Function

Approach 1: Helper Function

# Helper Function that returns the name if its length is 4
def keepName(name):
    if len(name) == 4:
        return name

def friend(x):
    return list(filter(keepName, x))

We can define a helper function in combination with the built-in filter function in Python to solve this problem. The helper function will take in a name (of type string) and return the name if its length is 4.

Using filter(), we can filter the original list of names to exclude names that are not length 4. We can then make the result a list using the list() function and return the value to get an array of names with lengths equal to 4.

Approach 2: Lambda Function

def friend(x):
    return list(filter(lambda f: f if len(f) is 4 else None, x))

We can alternatively use a lambda function as a parameter to the built-in filter function in Python. The lambda function has the formal parameter f and returns f if its length is equal to 4, and returns None if otherwise.

We can then use filter() in the same way as before. This is a more succinct way of writing the solution.