Python Forum
remove elements method not working - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: remove elements method not working (/thread-29000.html)



remove elements method not working - spalisetty06 - Aug-13-2020

Hello,
I am trying to use remove() to remove elements from the list but it is not happening. Kindly help.

l = [10, 10, 10, 10, 20, 20, 30]
x = int(input("Enter element to remove "))
for i in l:
    if i == x:
        l.remove(i)
print(l)
Output:
Enter element to remove 10 [10, 10, 20, 20, 30]



RE: remove elements method not working - buran - Aug-13-2020

never change list while iterating over it. Iterate over copy of the list


RE: remove elements method not working - spalisetty06 - Aug-13-2020

Thank you but I didn't understand much. I am new to python. Don't mind.


RE: remove elements method not working - buran - Aug-13-2020

Maybe this will make it a bit clear.
spam = ['a', 'b', 'c', 'd']

for char in spam:
    print(f'current char:{char}')
    if char in 'ab':
        spam.remove(char)
    print(f'current state of list: {spam}')
Output:
current char:a current state of list: ['b', 'c', 'd'] current char:c current state of list: ['b', 'c', 'd'] current char:d current state of list: ['b', 'c', 'd']
It's similar with what you do, but with chars, to make it more clear. Based on your logic, it should remove chars 'a' and 'b'.
but after removing 'a', now second element in list is already 'c', so it never visit 'b'.

what to do
spam = ['a', 'b', 'c', 'd']

for char in spam[::]: # iterate over a copy of the list
    print(f'current char:{char}')
    if char in 'ab':
        spam.remove(char)
    print(f'current state of list: {spam}')
Output:
current char:a current state of list: ['b', 'c', 'd'] current char:b current state of list: ['c', 'd'] current char:c current state of list: ['c', 'd'] current char:d current state of list: ['c', 'd']



RE: remove elements method not working - deanhystad - Aug-13-2020

Try this:
numbers = [1, 2, 3, 4, 5, 6, 7]
for i in numbers:
    numbers.remove(i)
print(numbers)
Why is every other number removed? Think about how a for loop might be indexing through a list and what happens tot he list when you remove an item. I use pencil and paper when trying to understand this stuff. Adding lots of print commands can be helpful too.

If someone tells you "never change list while iterating over it. Iterate over copy of the list" you should not accept as truth and try to determine why. Then you'll no longer be able to claim "I didn't understand much."