How can I remove all the numbers in a list except for 1 number (Python)?

Viewed 1611

I want my code to remove every single number in a list except for a specific number, which is 3. Instead it removes certain numbers but majority of them still remain in the list.

myList = [0,1,2,3,4,5]
i = 0
for i in myList:
    print(i)
    if i != 3:
        myList.remove(i)
    else:
        continue
    i += 1
    print(myList)
3 Answers

You've got a few issues. First, you're trying to modify the list in place, as you're trying to process it. You can fix that by changing:

for i in myList:

to:

for i in myList[:]:

That will allow your code to give the desired result. It makes a "copy" of the list over which to iterate, so you can modify the original list without messing up your iteration loop.

The other thing to note is that you assign a value to i in the for loop, but then you manually change it after your if-else block. That change gets discarded when you go back to the top of the loop.

Also, you're else: continue prevents incrementing i, but it doesn't matter, because that incremented value was just getting tossed anyway.

So... commenting out some of the unnecessary stuff gives:

myList = [0,1,2,3,4,5]
# i = 0
for i in myList[:]:
    print(i)
    if i != 3:
        myList.remove(i)
    # else:
        # continue
    # i += 1
    print(myList)

You have a couple of problems. First, the for loop iterates the list values, not its index. You can use enumerate to get both the index and the value. Second, if you delete values in a list, its remaining elements are shifted down by 1 but since the iterator also increments by 1, you miss a value. A trick is to iterate the list in reverse so that any deleted values have already been iterated.

>>> myList = [0,1,2,3,4,5]
>>> mlen = len(myList)
>>> for i, v in enumerate(reversed(myList), 1):
...     if v != 3:
...         del myList[mlen-i]
... 
>>> 
>>> myList

But this operation is slow. If you don't need to modify the original list, use a list comprehension

>>> myList = [0,1,2,3,4,5]
>>> myList = [v for v in myList if v==3]
>>> myList
[3]

The issue is you are removing elements from the list you are iterating over. So your loop won't iterate over the entire list.

Related