James Hallen
James Hallen

Reputation: 5014

Efficient way to compare elements in 2 lists

I want to compare entries in 2 lists:

for example:

for key in keys:
        for elem in elements:
            #Find a key in common with 2 lists and write the corresponding value
            if key == elem:
                 do something
            #Iterate through elements unit the current "key" value is found.
            else:
                 pass

Problem with this method is that it is very slow, is there a faster way to do this?

*Assuming len(keys) > len(elements)

Upvotes: 2

Views: 128

Answers (2)

Blender
Blender

Reputation: 298562

Turn them into sets:

set1 = set(keys)
set2 = set(elements)

And now you can find their intersection:

set1.intersection(set2)

The sets won't preserve order, so you'll get back just the common elements.

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251176

Use sets, and then set intersection will return the common elements.

Set intersection is an O(min(len(s1), len(s2)) operation.

>>> s1 = range(10)
>>> s2 = range(5,20)
>>> set(s1) & set(s2)  #set intersection returns the common keys
set([8, 9, 5, 6, 7])   # order not preserved 

Upvotes: 3

Related Questions