can you use the del statement inside a for loop in python

Question:

I want to remove the last two elements using the declaration of del

Beatles = ['John Lennon', 'Paul McCartney', 'George Harrison', 'Stu Sutcliffe', 'Pete Best']
for i in range(len(Beatles)):
    if Beatles[i] == 'Stu Sutcliffe' or Beatles[i] == 'Pete Best':
        print(i,Beatles[i]) #I print the index, to see if it is correct.
        del Beatles[i]
print("List:", Beatles)

When I run it I get the following message:

if Beatles[i] == 'Stu Sutcliffe' or Beatles[i] == 'Pete Best':
IndexError: list index out of range

It tells me that it is out of range, but it is strange since I visually validated that the index to be deleted is correct, I don’t know if the instruction does not work inside the loop, since outside it works by passing the index [3] and [4].

del Beatles[3]
del Beatles[4]
Asked By: Miguel Angel Villa

||

Answers:

You need use a while loop

Beatles = ['John Lennon', 'Paul McCartney', 'George Harrison', 'Stu Sutcliffe', 'Pete Best']
i = 0
while i < len(Beatles):
    if Beatles[i] == 'Stu Sutcliffe' or Beatles[i] == 'Pete Best':
        print(i,Beatles[i]) #I print the index, to see if it is correct.
        del Beatles[i]
    else:
        i = i + 1
print("List:", Beatles)

result

3 Stu Sutcliffe
3 Pete Best
List: ['John Lennon', 'Paul McCartney', 'George Harrison']
Answered By: CameL
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.