Remove duplicates


#1


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/4?curriculum_id=4f89dab3d788890003000096

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:
        results.append(element)
        for i in range(0,len(results)):
            for result in results:
                if result == results[i]:
                    del(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.


#2

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.


#3

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:


#4

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