Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python maintain order in intersection of lists

Tags:

python

list

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
like image 243
add-semi-colons Avatar asked Apr 20 '15 18:04

add-semi-colons


People also ask

Do python lists maintain order?

Lists Are Ordered It is an ordered collection of objects. The order in which you specify the elements when you define a list is an innate characteristic of that list and is maintained for that list's lifetime.

Does python set preserve order?

Unlike lists, ordinary sets do not preserve the order in which we insert the elements. This is because the elements in a set are usually not stored in the order in which they appear.

Can we use intersection in list?

Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists.


2 Answers

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.

like image 152
Mazdak Avatar answered Oct 19 '22 08:10

Mazdak


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]
like image 28
Steven Rumbalski Avatar answered Oct 19 '22 07:10

Steven Rumbalski