w3resource

Python: Find the nested lists elements, which are present in another list using lambda

Python Lambda: Exercise-40 with Solution

Write a Python program to find the nested list elements, which are present in another list using lambda.

Sample Solution:

Python Code :

# Define a function 'intersection_nested_lists' that finds the intersection of elements between two nested lists
def intersection_nested_lists(l1, l2):
    # Use list comprehension with a nested filter to find elements in each sublist of 'l2' present in 'l1'
    # For each sublist in 'l2', filter elements that are present in 'l1' and create a list of these elements
    result = [list(filter(lambda x: x in l1, sublist)) for sublist in l2]
    
    # Return the resulting nested list
    return result

# Create two lists: 'nums1' containing integers and 'nums2' containing nested lists of integers
nums1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
nums2 = [[12, 18, 23, 25, 45], [7, 11, 19, 24, 28], [1, 5, 8, 18, 15, 16]]

# Print the original lists 'nums1' and 'nums2'
print("\nOriginal lists:")
print(nums1)
print(nums2)

# Find the intersection of elements between the nested lists in 'nums2' and 'nums1' using the function
print("\nIntersection of said nested lists:")
print(intersection_nested_lists(nums1, nums2)) 

Sample Output:

Original lists:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[[12, 18, 23, 25, 45], [7, 11, 19, 24, 28], [1, 5, 8, 18, 15, 16]]

Intersection of said nested lists:
[[12], [7, 11], [1, 5, 8]]

Python Code Editor:

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

Previous: Write a Python program to find the elements of a given list of strings that contain specific substring using lambda.
Next: Write a Python program to reverse strings in a given list of string values using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/python-exercises/lambda/python-lambda-exercise-40.php