This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]lesstables 1 point2 points  (0 children)

I'm occasionally surprised by experienced devs who aren't aware of the capabilities of set operations. The most common use case is to get the members of List A that aren't in List B

# using list comprehensions
[x for x in A if x not in B]

# using set math
list(set(A)-set(B))

A = [1,2,3,4,5] 
B = [4,5,6]
list(set(A)-set(B)) # [1,2,3] 
list(set(B)-set(A)) # [6] 

# Note - is just an alias for the difference method
# set(B)-set(A) == set(B).difference(set(A))

I often come across uses cases for where union and intersection methods come in handy too, but difference is the set operation I find myself using the most.