Use in keyword or set.difference() or set.symmetric_difference() to find list difference in Python. The difference between the two lists means is one list containing the items that are not the second list.
Python list difference examples
Simple example code.
Use the in keyword
list1 = [1, 2, 4] list2 = [4, 5, 0] list_diff =  for item in list1: if item not in list2: list_diff.append(item) print(list_diff)
Use set.difference() method
First, convert both lists into sets and then use the set difference method to get the difference between both sets. Last converts the set difference into a list.
list1 = [1, 2, 4] list2 = [4, 5, 0] set_diff = set(list1) - set(list2) list_diff = list(set_diff) print(list_diff)
Output: [1, 2]
Use set.symmetric_difference() method
Same as above method convert both lists into sets then use set symmetric_difference() get the symmetric difference between both sets.
list1 = [1, 2, 4] list2 = [4, 5, 0] sd = set(list1).symmetric_difference(set(list2)) list_diff = list(sd) print(list_diff)
Output: [0, 1, 2, 5]
Do comment if you have any doubts and suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.