Python: Remove specific words from a given list using lambda
Python Lambda: Exercise-50 with Solution
Write a Python program to remove specific words from a given list using lambda.
Sample Solution:
Python Code :
# Define a function 'remove_words' that removes specified words from a list
def remove_words(list1, remove_words):
# Use 'filter' with a lambda function to filter out words from 'list1' that are not in 'remove_words'
# Create 'result' containing words from 'list1' that are not in 'remove_words'
result = list(filter(lambda word: word not in remove_words, list1))
# Return the filtered list
return result
# Create a list 'colors' containing words representing colors
colors = ['orange', 'red', 'green', 'blue', 'white', 'black']
# Create a list 'remove_colors' containing words to be removed from the 'colors' list
remove_colors = ['orange', 'black']
# Print the original list 'colors'
print("Original list:")
print(colors)
# Print the list of words to be removed 'remove_colors'
print("\nRemove words:")
print(remove_colors)
# Remove the specified words from the 'colors' list using the 'remove_words' function and print the result
print("\nAfter removing the specified words from the said list:")
print(remove_words(colors, remove_colors))
Sample Output:
Original list: ['orange', 'red', 'green', 'blue', 'white', 'black'] Remove words: ['orange', 'black'] After removing the specified words from the said list: ['red', 'green', 'blue', 'white']
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to count the occurrences of the items in a given list using lambda.
Next: Write a Python program to find the maximum and minimum values in a given list of tuples using lambda function.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/lambda/python-lambda-exercise-50.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics