Remove duplicates


Oops, try again. remove_duplicates([4, 5, 5, 4]) returned [] instead of [4, 5

The code needs to remove duplicates of list elements but can't figure out...

def remove_duplicates(elements):
    results = []
    for element in elements:
        for i in range(0,len(results)):
            for result in results:
                if result == results[i]:
    return results
print remove_duplicates([2,2,2,3,4,5])
Output : [] 
#An empty list
I know I just create the list then just delete them back :D. I don't know how to make it stop for the originals.


Your first three lines of code are perfect! What you can do to make this work is to remove lines 4-8 and take a new approach.

Use an if statement to see if the element is not in the results, then append the element to the results. After that you can return the results.


Just above that, see if the element is not in results. If so, append that to the list.

You can safely remove the two nested for-loops.

Then, return the results :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.