0

I created a function to take a list as input and remove the duplicates without creating a new array. However, the output is wrong. How can I fix this? and is there a simpler way to do it? I am new to Python

def remove_duplicates(duplicatelist):
    for i in duplicatelist:
        num = 0
        while num < len(duplicatelist)-1:
            #the following line checks to see if there is a 
            #duplicate. It also makes sure that num = i is not being
            #counted as  duplicate because if you have a value of 2 at index 2,
            #then this should not be counted as a duplicate if it's the only one
            if i == duplicatelist[num] and i !=num :
                duplicatelist.remove(duplicatelist[num])
            num = num + 1
    print(duplicatelist)

remove_duplicates([1, 1, 2, 3, 3, 4, 5, 6, 6, 6, 7])
#output is: [1, 3, 4, 6, 7] but this is wrong.
hershey10
  • 77
  • 4
  • 1
    Don't modify a list as you iterate over it. – Scott Hunter Feb 24 '22 at 20:36
  • As the links to the duplicate answers show this can be done. Be cautious about modifying the **order** or **length** of a list as a side effect. The code skipped 2 because the 2 started in duplicatelist[2]. When the "1" is deleted from duplicatelist[1] "2" is moved to position duplicatelist[1]. "3" is now at duplicatelist[2]. – Carl_M Feb 24 '22 at 21:24

1 Answers1

0

This is different from what you're trying, but if you use the set data structure, it would automatically filter duplicates. Here's one dumb way to do it:

def remove_duplicates(duplicatelist):
    duplicatelist = list(set(duplicatelist))  # first convert to set, then back to a list, reusing the variable name
    print(duplicatelist)

remove_duplicates([1, 1, 2, 3, 3, 4, 5, 6, 6, 6, 7])

Source: https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset

eccentricOrange
  • 876
  • 5
  • 18