How can I use “not in” to remove duplicates from a list?


#1

Question

How can I use “not in” to remove duplicates from a list?

Answer

When we use not in, it results in True only if the object on the left is not present in the object on the right. For example, if we have a list of numbers and want to know if the number 10 is present in it, and print a message to the user if it is not, we could write:

if 10 not in my_list:
  print "10 not found!"

To expand on that, we can check for duplicates by creating an empty list to put our non-duplicate numbers into. Then, inside of a loop that goes through our input list, we’d do a check similar to the code above and look for the current loop variable value to not be in our output list. If it isn’t, we append() that value to it!
Then be sure to return that output list outside of the loop, otherwise your code will stop early!


FAQ: Learn Python - Practice Makes Perfect - Remove_duplicates