E
E
EnotShow2021-09-09 18:58:21
Python
EnotShow, 2021-09-09 18:58:21

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)

but after validation, it doesn't unnecessarily delete everything. To remove all unnecessary, 2 passes are required. Why does it work the way it does and where did I go wrong?

This is what I get after the first pass:
['some', 'leave', None, 'leave', 'leave']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmshar, 2021-09-09
@EnotShow

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)

Here's the output: Usually they talk about this at the very first lecture on working with lists. Well, or they write at the beginning of the corresponding paragraph in the books.
['leave', 'leave', 'leave']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question