0

I have looked around and found the

 if numbers.count(x) >= 2: 
    numbers.remove(x) 
 print(numbers)

but I don't want to use that. I think lazy-ier way is to go like this:

numbers = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 2, 5, 12]
numbers.sort()
print(numbers)
duplicate = 0
for each_item in numbers:
  if duplicate == each_item:
    numbers.remove(each_item)
  else:
    duplicate += 1
print(numbers)

I, first, sort the list then print it for manual comparison. I add a variable called duplicate and set it to 0. I go thru the loop for each number in the list numbers. If I find the duplicate's value same as a number in the list, I remove it and go thru the loop, else I increase the value by 1 and print the list.

The problem is if there are more than 2 duplicates in the list it doesn't work. Which I don't understand why. I run the code in my head and it should work "flawlessly"?

Thank you for your time sensei's

Current output is;

[1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 12]
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 12]
Deniz
  • 17
  • 5

2 Answers2

2

Use a set to make things easy:

numbers = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 2, 5, 12]
s = set(numbers)
print(list(s))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 12]
NYC Coder
  • 7,424
  • 2
  • 11
  • 24
  • Well, it works but I wanted to find the problem with my logic. Can you tell what's with my way? I can't – Deniz Aug 01 '22 at 18:13
1

You are changing an iterable as you iterate over it. That causes unpredictable behavior, like "skipping" an item in that list. There's plenty of resources on the internet describing the details (for instance).

Instead, iterate over a copy:

for each_item in numbers[:]:
    (...)
rafaelc
  • 57,686
  • 15
  • 58
  • 82