Filtering Strings by Length

Write a Python lambda function that takes a list of strings and an integer n, and filters out all strings less than n characters long. Return the list.

Example 1:

Input: ['Hello', 'World', 'Python', 'Programming'], 6

Output: ['Python', 'Programming']

Example 2:

Input: ['Apple', 'Banana', 'Cherry', 'Dates'], 6

Output: ['Banana', 'Cherry']

Use the filter() function with a lambda function to select only the strings longer than n.

# Define the lambda function
filter_by_length = lambda words, n: list(filter(lambda x: len(x) >= n, words))

# Test the function
print(filter_by_length(['Hello', 'World', 'Python', 'Programming'], 6)) # Output: ['Python', 'Programming']
print(filter_by_length(['Apple', 'Banana', 'Cherry', 'Dates'], 6)) # Output: ['Banana', 'Cherry']

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!