sodiumnitrate
sodiumnitrate

Reputation: 3131

How to get common elements of two lists, which are themselves lists in python

I have two lists of lists:

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]

and I want to get their intersection, i.e., [[3,1],[1,4],[1,'a']]. How can I do this?

Upvotes: 0

Views: 92

Answers (3)

Garrett R
Garrett R

Reputation: 2662

Assuming the inner elements will always be in the same order.

out = set(map(tuple, l1)).intersection(map(tuple, l2))

Output

set([(1, 'a'), (3, 1), (1, 4)])

Note that the above returns a set of tuples, not lists. But you can easily convert them back to lists if needed:

map(list, out)

Upvotes: 1

GLHF
GLHF

Reputation: 4035

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]
intersection = []
for x in l1:
    if x in l2:
        intersection.append(x)
print (intersection)

Use for loop find same elements and append them into another list.

Output;

[[3, 1], [1, 'a'], [1, 4]]
>>> 

Or shorter way, use list comprehensions;

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]

print ([x for x in l1 if x in l2])

Upvotes: 2

timgeb
timgeb

Reputation: 78650

Considering your clarification comments on the question, do it like this:

Convert one of the lists to a set (for the O(1) lookup time), then employ a list comprehension.

>>> l2_s = set(map(tuple, l2))
>>> [x for x in l1 if tuple(x) in l2_s]
[[3, 1], [1, 'a'], [1, 4]]

Upvotes: 1

Related Questions