How we have to remove the elements that occur once in one list if we take two lists ?

Submitted 3 years, 7 months ago
Ticket #121
Views 237
Language/Framework Python
Priority Medium
Status Closed

 I have two lists, l1 and l2. I want to perform l1 - l2, which returns all elements of l1 not in l2.

EXAMPLE:

L1=[2,4,8,1,17,10] 

L2=[17,9,1,8,32,90]

L1-L2 should give the answer [2,4,10]

Submitted on Sep 10, 20
add a comment

2 Answers

L1=[2,4,8,1,17,10] 

L2=[17,9,1,8,32,90]

print(list(set(L1)-set(L2)))

Submitted 3 years, 7 months ago

the solution using `set` isn't entirely correct. Python's `set` would remove duplicate values, meaning it's destructive by nature.
The pythonic solution for this would be:

>>> l1 = [1,1,2,3,4,5,6,7,8]
>>> l2 = [2,4,6,8,0]
>>> result = [x for x in l1 if x not in l2]
>>> result
[1, 1, 3, 5, 7]

Submitted 3 years, 7 months ago

@Hussam, Thanks for your answer. we are really glad you joined as a Techion and helping our community.
@18-595, if everything looks, can you please close the ticket

- Vengat 3 years, 7 months ago


Latest Blogs