2

I have two lists of lists with same shape.

list1 = [[1,2,3], [], [4,5], []]
list2 = [[1,2], [7], [4,5], []]

I need this list of lists:

[[1,2], [], [4,5], []]

How I can get it?

P.S.: These topics didn't help me:

Python - Intersection of two lists of lists

Find intersection of two nested lists?

Carlo Pazolini
  • 315
  • 1
  • 8

4 Answers4

5

Assume each list in list1 and list2 contains only distinct elements and you do not care about the ordering of the elements in output, you can use set intersection to help you:

output = [list(set(l1) & set(l2)) for l1, l2 in zip(list1, list2)]
adrtam
  • 6,991
  • 2
  • 12
  • 27
4

Loop through and use sets:

list1 = [[1,2,3], [], [4,5], []]
list2 = [[1,2], [7], [4,5], []]

intersections = [list(set(s1)&set(s2)) for s1, s2 in zip(list1, list2)]

outputs:

[[1, 2], [], [4, 5], []]
Grant Williams
  • 1,469
  • 1
  • 12
  • 24
4

Get each sub-list by index of the shorter list.

[list(set(list1[x]) & set(list2[x])) for x in range(min(len(list1), len(list2)))]
# [[1, 2], [], [4, 5], []]

This will result in a list with the same length as the shortest input.

Alex
  • 6,610
  • 3
  • 20
  • 38
0

here it is:

list1 = [[1,2,3], [], [4,5], []]
list2 = [[1,2], [7], [4,5], []]
new_list = []

for i in range(len(list1)):
    inter = [x for x in list1[i] if x in list2[i]]
    new_list.append(inter)

print(new_list)

output:

[[1, 2], [], [4, 5], []]
Mahmoud Elshahat
  • 1,873
  • 10
  • 24