find the differences in a list in python

To find the differences between two lists, convert them into sets and use set operations. Here's an example:

main.py
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

# Find the differences between list1 and list2
difference = set(list1) - set(list2)

print(difference) # Output: {1, 2}
169 chars
8 lines

In this example, we first convert list1 and list2 into sets using the set() function. We then find the difference between the two sets using the - operator. Finally, we print the result, which is a set containing the elements that are in list1 but not in list2.

To find the differences between multiple lists, you can use set comprehensions:

main.py
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
list3 = [4, 5, 6, 7, 8]

# Find the differences between list1, list2, and list3
difference = {x for x in list1 if x not in list2.union(list3)}

print(difference) # Output: {1, 2}
227 chars
9 lines

In this example, we use set comprehensions to create a set of elements that are in list1 but not in the union of list2 and list3.

gistlibby LogSnag