-1
data = [1, 2, 3, 4, 5]
for x in data:
        print(x)
        if data.count(x) < 2:
                data.remove(x)

Hello Guys,

so I am currently working through py.checkio.org and am at a point where I have to remove all the numbers that are unique in a list.

When I run my code without the if statement I get an output counting from 1 to 5. But once I run the for loop with the if statement the for loop only runs through the data for every second number and my output is 1 3 5. Can anyone please tell me what is happening here?

  • 1
    Very relevant question: [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating). TL;DR: Never remove elements from the list you're currently iterating on. Instead, find a workaround. For instance, make a copy of the original list, and iterate on the copy. – Stef Oct 28 '21 at 13:06
  • 1
    A simile: Removing elements of the list you're iterating on is kinda like sawing the tree branch you're sitting on. You end up falling from the tree. – Stef Oct 28 '21 at 13:08

2 Answers2

0

While the from @Stef and @0x5453 are both relevant to your problem. The comment from @ConnorTJ is patently wrong. The remove function does not remove the item at the index but the first occurrence of the item.

To answer your question, about what's going on here, let[s examine your code: The first pass through the value of x is 1 You print the value of x You then test to see if the number of occurrences of x is less than 2 Since the answer is yes, you proceed to remove the item from the list.

The second pass through the list the For loop picks up the next value in the list (at index 1) which is now the value 3 You print the value 3 You check to see if the count of 3 is less than 2 Since the count is less you remove that item from the list.

This process than continues

itprorh66
  • 3,110
  • 4
  • 9
  • 21
0

Simple solution, use filter()

Construct an iterator from those elements of iterable for which function returns true

it returns a list of the list items that the function returned true for.

example:

x = [1,1,2,2,3,4]
x = filter(lambda f: (x.count(f)<2), x)
x = list(x)
print(x)

or in short: print(list(filter(lambda f: (x.count(f)>=2),x)))

output is [1,1,2,2]

Relenor
  • 39
  • 8