Click here to Skip to main content
15,896,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Python
numbers = [2,2,4,6,3,4,6,1]
for num in numbers:
    if num in numbers:
       numbers.remove(num)
print(numbers)


# why output shows
[2, 4, 6, 1]

here in this output 3 is missing. Please can anybody explain it?

What I have tried:

i wrote a program in python and getting output as
[2, 4, 6, 1]

and in this 3 is missing why?
Posted
Updated 14-Jan-22 22:19pm
v3

I'm not a Python programmer, but in general removing elements in a for loop is a bad idea, this will confuse the for loop.
You can do it, but start at the end of the array, see: Backward iteration in Python - GeeksforGeeks[^]
 
Share this answer
 
The best way to understand what is happening is to get to know the debugger. Depending on the tools you use you most likely have debugger but if not, there are plenty available online.

If you use the debugger and go through the execution line-by-line you'll notice that you always check the existence of the number at hand against the whole array, not just the remaining portion of it. For example if you're in the first number 2 it exists, actually twice, so you remove the first element.

The next question you'll bump into is, why isn't every number eliminated? The reason is that when you're in the first element, you find it in the array but when you remove the first element, the second element becomes the first and then your loop is advanced to the next element, in this case to number 4, which previously was element 3 but now is element 2.

This explains why 3 is eliminated from the array even though other numbers look like they would be behaving correctly.
 
Share this answer
 
You cannot modify a list while iterating over it. You should create a new list and copy the numbers over checking first if it already exists.

Python
numbers = [2,2,4,6,3,4,6,1]
newnums = []
for num in numbers:
    if num not in newnums:
        newnums.append(num)
print(sorted(newnums))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900