Python: Get the difference between two given lists, after applying the provided function to each list element of both
Python List: Exercise - 222 with Solution
Write a Python program to get the difference between two given lists, after applying the provided function to each list element of both.
- Create a set, using map() to apply fn to each element in b.
- Use a list comprehension in combination with fn on a to only keep values not contained in the previously created set, _b.
Sample Solution:
Python Code:
def difference_by(a, b, fn):
_b = set(map(fn, b))
return [item for item in a if fn(item) not in _b]
from math import floor
print(difference_by([2.1, 1.2], [2.3, 3.4], floor))
print(difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']))
Sample Output:
[1.2] [{'x': 2}]
Flowchart:

Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to randomize the order of the values of an list, returning a new list.
Next: Write a Python program to create a list with the non-unique values filtered out.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Returns True if the provided function returns True for every element in the list, False otherwise:
Example:
def tips_every(lst, fn=lambda x: x): return all(map(fn, lst)) print(tips_every([2, 4, 3], lambda x: x > 1)) print(tips_every([1, 2, 3]))
Output:
True True
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises