Mirage
Mirage

Reputation: 31568

How to remove the items from list in python based on other list

I have

list1 = [var1,var2,var3,var4,var5]

and other

list2 = [var4, var2]

Now i want to subtract them so that final result is

list1 = [var1,var3,var5]

Upvotes: 0

Views: 69

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

Use list comprehension this way:

l1 = [var1,var2,var3,var4,var5]
l2 = [var4, var2]

diff = [x for x in l1 if x not in l2]

Upvotes: 4

Denis
Denis

Reputation: 7343

You can convert your lists in sets and get difference between them

list1 = [1,2,3,4]
list2 = [1, 3]
list1 = set(list1)
list2 = set(list2)
list1.difference(list2)
OUTPUT: set([2, 4])

Upvotes: 0

Vivek S
Vivek S

Reputation: 5550

Assumin lists don't have duplicate items,

list(set(list1)-set(list2))

Upvotes: 3

Related Questions