w3resource

Python: Find the elements of a given list of strings that contain specific substring using lambda


Write a Python program to find the elements of a given list of strings that contain a specific substring using lambda.

Sample Solution:

Python Code :

# Define a function 'find_substring' that filters elements containing a substring in a list
def find_substring(str1, sub_str):
    # Use the 'filter' function with a lambda to filter elements in 'str1' containing 'sub_str'
    result = list(filter(lambda x: sub_str in x, str1))
    
    # Return the filtered list
    return result

# Create a list 'colors' containing strings representing different colors
colors = ["red", "black", "white", "green", "orange"]

# Print the original list 'colors'
print("Original list:")
print(colors)

# Set a substring 'sub_str' to search within the list 'colors' and print it
sub_str = "ack"
print("\nSubstring to search:")
print(sub_str)

# Print elements from 'colors' that contain the specific substring using the 'find_substring' function
print("Elements of the said list that contain the specific substring:")
print(find_substring(colors, sub_str))

# Change the substring 'sub_str' to search and print it
sub_str = "abc"
print("\nSubstring to search:")
print(sub_str)

# Print elements from 'colors' that contain the new specific substring using 'find_substring' function
print("Elements of the said list that contain the specific substring:")
print(find_substring(colors, sub_str)) 

Sample Output:

Original list:
['red', 'black', 'white', 'green', 'orange']

Substring to search:
ack
Elements of the said list that contain specific substring:
['black']

Substring to search:
abc
Elements of the said list that contain specific substring:
[]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to remove all elements from a given list present in another list using lambda.
Next: Write a Python program to find the nested lists elements, which are present in another list using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.