# Python find elements in one list that are not in the other

I need to compare two lists in order to create a new list of specific elements found in one list but not in the other. For example:

```
main_list=[]
list_1=["a", "b", "c", "d", "e"]
list_2=["a", "f", "c", "m"]
```

I want to loop through list_1 and append to main_list all the elements from list_2 that are not found in list_1.

The result should be:

```
main_list=["f", "m"]
```

How can I do it with python?

(1) You can use NumPy's `setdiff1d`

(`array1`

,`array2`

,`assume_unique`

=`False`

).

This yields the unique values in `array1`

that *are not* in `array2`

. `assume_unique`

is `False`

by default (set this to `True`

if *you know* that both `array1`

and `array2`

are unique).

For those who want answers to be sorted:

(1.1) setting `assume_unique`

to `False`

**automatically** spews out a sorted array.

(1.2) setting `assume_unique`

to `True`

yields a (possibly) unsorted array.

To address this issue, I've made a custom function:

```
import numpy as np
def setdiff_sorted(array1,array2,assume_unique=False):
ans = np.setdiff1d(array1,array2,assume_unique).tolist()
if assume_unique:
return sorted(ans)
return ans
```

If you are concerned with the **unique** elements (based on the response of Chinny84), then:

```
list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "f", "c", "m"]
main_list = setdiff_sorted(list_2,list_1)
```

(2) Otherwise, use `main_list = setdiff_sorted(list_2,list_1, assume_unique=True)`

Both answers will give you `["f", "m"]`

.

**SIDE NOTES:**

(a) The custom function `setdiff_sorted`

returns a list (compared to an array in NumPy's `setdiff1d`

).

(b) Things will be different if either of the two lists is **not** unique.

Say `list_2 = ["a", "f", "c", "m", "m"]`

.

Answer (1) yields `["f", "m"]`

BUT answer (2) gives `["f", "m", "m"]`

(because the uniqueness of each element in `list_2`

is immaterial). Still, both answers are sorted.

From: stackoverflow.com/q/41125909