Example difference between two lists in Python
Simple example code getting the difference between two lists results in a list containing the items that are in the first list but not the second.
Use the in keyword
Use a for-loop to iterate through the first list and check if the item is not in the second list.
list1 = ['One', 'Two', 'Three', 'Four'] list2 = ['One', 'Two'] list_difference =  for item in list1: if item not in list2: list_difference.append(item) print(list_difference)
Using list comprehension
It is a more compact implementation and recommend way compare to the upper example.
list1 = ['One', 'Two', 'Three', 'Four'] list2 = ['One', 'Two'] list_difference = [item for item in list1 if item not in list2] print(list_difference)
Output: [‘Three’, ‘Four’]
Using set difference()
You have to convert both lists into sets and then use the set difference() where the set is the first set and s is the second set to get the difference between both sets.
list1 = [1, 2, 4] list2 = [4, 5, 6] set_difference = set(list1) - set(list2) list_difference = list(set_difference) print(list_difference)
Output: [1, 2]
Do comment if you have any doubts or 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.