8

I have a list A and list B, I want to get common elements from the two lists but want when I get the common elements they should maintain the order of List A.

First I started with converting them in to set and taking the intersection but that had the problem of maintaining the order.

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

so I decided to do list comprehension:

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

I am getting

IndexError: too many indices for array
Alex A.
  • 5,466
  • 4
  • 26
  • 56
add-semi-colons
  • 18,094
  • 55
  • 145
  • 232
  • Your error is irrelevant to your comprehension statement. – Abhijit Apr 20 '15 at 18:29
  • 1
    I would actually argue that this is _not_ a duplicate since the OP wants to maintain the original ordering, which none of the answers to the linked question do. – Alex A. Apr 20 '15 at 18:34
  • 2
    Cannot reproduce. `A = [1, 2, 3, 3, 2]`, `B = [2, 3]`, `[i for i in A if i in B]` gives `[2, 3, 3, 2]`. Can you provide sample data to reproduce your issue? – Łukasz Rogalski Apr 20 '15 at 18:45
  • 1
    @AlexA. Thank You so much of not being so quick to write off as a duplicate. I think the title you used is exactly what I should have used at first place. – add-semi-colons Apr 20 '15 at 19:32

2 Answers2

10

As a general answer for such problems You can use sorted function with lambda x:A.index(x) as its key that will sort the result based on the order of list A:

>>> common = sorted(set(A).intersection(B) ,key=lambda x:A.index(x))

Also Note that you don't need use set(B) for intersection.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • `intersection(B)` should be `intersection(set(B))` ? or you assume B is already a set..? – add-semi-colons Apr 20 '15 at 18:42
  • 2
    @Null-Hypothesis: As long as `A` is a set, it has an intersection method. It's legit to do intersections between sets and lists as is done here. – Alex A. Apr 20 '15 at 18:44
  • 2
    `key=A.index` should work without using lambda. I think that sorting using `A.index` changes the performance characteristics to quadratic, which will make this less optimal for very large with large intersections. – Steven Rumbalski Apr 20 '15 at 19:36
  • What if there are some duplicates in the list? – EnesZ Feb 28 '23 at 18:44
2

Your code (common = [i for i in A if i in B]) works just fine. Perhaps what you wrote in your question was not the exact code that raised the IndexError.

You can speedup membership tests by making a set from B:

set_b = set(B)
common = [i for i in A if i in set_b]
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119