Carlo Pazolini
Carlo Pazolini

Reputation: 315

Get intersection of two lists of lists or empty list

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?

Upvotes: 2

Views: 631

Answers (4)

Mahmoud Elshahat
Mahmoud Elshahat

Reputation: 1959

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], []]

Upvotes: 0

Alex
Alex

Reputation: 7045

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.

Upvotes: 4

Grant Williams
Grant Williams

Reputation: 1537

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], []]

Upvotes: 4

adrtam
adrtam

Reputation: 7211

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)]

Upvotes: 5

Related Questions