For loops
For loops allow you to repeat a piece of code multiple times. You could easily just write a conditional and a print statement multiple times for each item in the list. A for loops allows you to write that piece of code once and have it repeated for each item in the list.
You can iterate over item in list2 by doing the following
for item in list2:
print(item)
item
is an arbitrary variable name that holds the value of the current item we are on, what follows in
is the list that we want to iterate over. print(item)
is the piece of code we want to repeat for each element in the list.
What this does is goes through every item in list2 and prints them but that is not what we want. We want to check to make sure that item is not in list1. This can be achieved through a conditional statement.
if item not in list1:
print(item)
Now we can join the two piece of code together.
for item in list2:
if item not in list1:
print(item)
Sets
Are a collection of items in no order where every item is unique. These sets are the same ones we encounter in mathematics, therefore we can perform mathematical set operations on them.
To go from a list of items to a set we use sList1 = set(list1)
sList1 is now of type set and stores the elements in list1. The same can be done for list2.
Now that we have sList1
and sList2
we want to eliminate any duplicates in the two for that we can take the difference of sList1
and sList2
and print them out as follows print(sList2-sList1)
.
We can do all of this in one step.
print( set(list2) - set(list1) )