0

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]
0

3 Answers 3

4

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]
Sign up to request clarification or add additional context in comments.

2 Comments

you could add l2 = set(l2) to speed up x not in l2 lookup.
yes sure - i know, but sometimes it is not so important - so i just tried to provide an option for OP
3

Assumin lists don't have duplicate items,

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

Comments

0

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.