How to Remove Duplicates in Lists in Python


Manipulating lists is a very common task for programmers. A programmer may need to search a list of words for duplicates and remove them. Being able to remove duplicates from a list in several languages is a must for anyone who wishes to pursue a career in software development. The Python programming language has several built-in features that simplify this task.

  • Open the IDLE text editor that comes with the Python Programming Language.

  • Declare a list of words at the top of the source code file, making sure to include duplicates. For example, you could write this:

    wordList = ["cat", "dog", "monkey", "dog", "cat"]

  • Declare an empty list below the previous list, like this:

    wordList2 =[]

  • Iterate over the first word list using a for loop, like this:

    for x in range(len(wordList)):

  • Iterate over the rest of the words in the list by using a nested for loop. You need to indent this for loop by pressing the tab key once, and then writing this next line of code:

    for y in range(x + 1, len(wordList)):

  • Test each word iterated over in the second for loop against the words iterated over in the first for loop. This is accomplished using an "if" statement, which must be indented using the tab key. The if statement can be written like this:

    if wordList[x] == wordList[y]:

  • Add duplicate words to the empty word list created in Step 3. This line of code needs to be indented using the tab key:


  • Hit the "Enter" key a couple of times and then hit "Delete" to remove all the indents and return the cursor to the left-hand side of the text editor.

  • Iterate through the second word list like this:

    for y in worldList2

  • Remove each word contained in the second word list from the first word list. This can be done by writing the following line, indented once with a tab key press:


  • Press "F5" to execute the script. The following lines are output:




Promoted By Zergnet



You May Also Like

Related Searches

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!