Answer the question
In order to leave comments, you need to log in
Why does the program remove objects from the list incorrectly?
Hello colleagues !
I began to study python and asked the following question: "How to remove from the list all objects except for certain ones?". sketched out an elegant solution,
my_list = ['some word', 'some', 'leave', 1, None, 'leave', True, 'leave', 'else']
for i in my_list:
if i != 'leave':
my_list.remove(i)
print(my_list)
['some', 'leave', None, 'leave', 'leave']
Answer the question
In order to leave comments, you need to log in
First, it is not the program that deletes objects incorrectly, it is you who wrote such a program that does not work correctly.
Secondly, no two passes are needed.
my_list = ['some word', 'some', 'leave', 1, None, 'leave', True, 'leave', 'else']
for i in my_list[::-1]:
if i != 'leave':
my_list.remove(i)
print(my_list)
['leave', 'leave', 'leave']
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question