Python - Intersection of multiple lists

PythonServer Side ProgrammingProgramming

In this article, we are going to see how to intersect two lists that contain multiple lists in different ways. Let's start in the traditional way.

Follow the below the steps to solve the problem

  • Initialize two lists with multiple lists
  • Iterate over the first list and add the current item in the new list if it presents in the second list as well.
  • Print the result.

Example

 Live Demo

# initializing the lists
list_1 = [[1, 2], [3, 4], [5, 6]]
list_2 = [[3, 4]]

# finding the common items from both lists
result = [sub_list for sub_list in list_1 if sub_list in list_2]

# printing the result
print(result)

If you run the above code, then you will get the following result.

Output

[[3, 4]]

We'll use the set to intersect two lists. Follow the below steps.

  • Convert two lists items into tuples using map.
  • Intersect two sets using intersection and map method.
  • Convert the result to list
  • Print the result.

Example

 Live Demo

# initializing the lists
list_1 = [[1, 2], [3, 4], [5, 6]]
list_2 = [[3, 4]]

# converting each sub list to tuple for set support
tuple_1 = map(tuple, list_1)
tuple_2 = map(tuple, list_2)

# itersection
result = list(map(list, set(tuple_1).intersection(tuple_2)))

# printing the result
print(result)

If you run the above code, then you will get the following result.

Output

[[3, 4]]

Conclusion

If you have any queries in the article, mention them in the comment section.

raja
Published on 13-Nov-2020 23:38:20
Advertisements