Ask coding questions

← Back to all posts
Can't figure out why this code won't loop properly.
LawrenceKaiser (0)

I have this code that should be removing any duplicate numbers so long as they are the same as one another & next to each other. It works the first time, but after that the loop stops outputting anything. Can anyone help me out with this?

Comments
hotnewtop
OldWizard209 (1498)

please attach the repl, so we understand the code properly.

OldWizard209 (1498)

Put a while loop and embed the for loop in it. And then put an if statement which stops once the values are un-duplicated. @LawrenceKaiser

LawrenceKaiser (0)

Something like this? I may have done this wrons as it doesn't seem to work. @OldWizard209

OldWizard209 (1498)

Your code is long and useless. You don't need all of that what you have written. Just use what Python offers. There is a dictionary function called fromkeys, which forms a dictionary with given key, value pairs. It normally ignores duplicates because one key, cannot be named to more than 1 value. So you can first change your list into a dictionary and back into a list after creating only keys, without values.

def remove_dupe(duplicatesList):
  newList = list(dict.fromkeys(duplicatesList))
  print(newList)
  
remove_dupe([1, 1, 1, 2, 4, 4, 4, 5, 2, 2, 2, 7])

Output: [1, 2, 4, 5, 7]

Now, this is the smallest code that will perform the action. But it takes a lot of time because first, it is a list, then a dictionary is formed, and then back into a list. Not the best option. The second option will be to use a for loop:

def remove_dupe(duplicatesList):
  newList = []
  for i in duplicatesList:
        if i not in newList:
            newList.append(i)

  print(newList)

remove_dupe([1, 1, 1, 2, 4, 4, 4, 5, 2, 2, 2, 7])

Output: [1, 2, 4, 5, 7]

To check which one takes more time, I wrote a simple script that checks.

import time

# <-- Method 1 -->

def remove_dupe1(duplicatesList):
    newList = list(dict.fromkeys(duplicatesList))
    print(newList)

start = time.time()
remove_dupe1([1, 1, 1, 2, 4, 4, 4, 5, 2, 2, 2, 7])

print(time.time() - start)

# <-- Method 2 -->

def remove_dupe(duplicatesList):
  newList = []
  for i in duplicatesList:
        if i not in newList:
            newList.append(i)

  print(newList)

start = time.time()
remove_dupe([1, 1, 1, 2, 4, 4, 4, 5, 2, 2, 2, 7])

print(time.time() - start)

Output:

[1, 2, 4, 5, 7]
8.821487426757812
[1, 2, 4, 5, 7]
3.814697265625

Method 2 is faster. You decide which one to use.

Please mark this answer as correct if it helps.
@LawrenceKaiser