halid.sert
halid.sert

Reputation: 63

Checking if an element exist in list

I have 2 lists(pandas.core.series.Series) and I want to list elements that doesn't exist in the other series. So I'm using 'not in' operator but it doesn't work and the code prints the whole list instead.

for i in list1:
  if i not in list2:
    print(i)

This code prints the whole list1 instead of printing elements that don't exist in list2. I know this should be a simple task but I'm stuck, can someone help me?

Upvotes: 0

Views: 68

Answers (3)

I demonstrate isin using ~ which means not in. The isin build a mask of true of false values then applied to the dataframe

list1 = pd.Series([1, 2, 3, 4, 5])
list2 = pd.Series([4, 5, 6, 7, 8])

print(list1[~list1.isin(list2)])

output

1 2 3

values of list1 are not in list2

Upvotes: 1

alparslan mimaroğlu
alparslan mimaroğlu

Reputation: 1490

You can just use sets and calculate the set difference.

set(list1).difference(set(list2))

Upvotes: 2

Nils Werner
Nils Werner

Reputation: 36859

You can use Pandas own Series.isin():

list1[~list1.isin(list2)]

Upvotes: 2

Related Questions