0
A = ['a','b','c'] 
B = ['d','b','e']

res = [i for i in A if i in B]

The above code does not work when the no of elements in A are 300000 and in B are 200000.

How can I solve it?

I also tried

res = {i for i in A if i in B}
res = list(res)

But still could not get the result.

4
  • 'Does not work' what does that mean? Commented Jul 17, 2014 at 10:03
  • Change B to a set first: B = set(B), then use the list comprehension. Commented Jul 17, 2014 at 10:04
  • 3
    What about A = set(A) and B = set(B), then do the intersection res = A & B? Commented Jul 17, 2014 at 10:04
  • 1
    And what type of comparation you want to do? When comparing lists I assume list are equal if elements are in the same order, too. Commented Jul 17, 2014 at 10:04

3 Answers 3

3

If preserving order and/or duplicates doesn't matter, then you can use

A = ['a', 'b', 'c']
B = ['d', 'e', 'f']
res = list(set(A) & set(B))

If order and/or duplicates does matter, then you can use

A = ['a', 'b', 'c']
B = ['d', 'e', 'f']
set_b = set(B)
res = [i for i in A if i in set_b]
Sign up to request clarification or add additional context in comments.

1 Comment

The second one can also be written (although somewhat ugily) as filter(set(B).__contains_, A)
3
A = ['a','b','c']
B = ['d','b','e']

set(A).intersection(B)

To get a list returned:

list(set(A).intersection(B))

intersection takes any iterable as an argument so you just need to make A a set.

Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference() will accept any iterable as an argument.

12 Comments

Should that be (set(B))?
@TimCastelijns, why would B need be a set?
This will remove the redundant items from A too and also affect the order if it matters, OP's first example is not doing that.
Not having B a set increases the time by 50% on my computer on a test case of the size OP specified
@deinonychusaur well if the OP has lists how are they going to magically become sets?
|
1

You are basically computing the intersection of two sets. Using the set data type for this will make this efficient:

A = {'a','b','c'}
B = {'d','b','e'}
res = A & B

2 Comments

how to put the lists A and B into {}?
@bas just do set(A) & set(B)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.