Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

del Beatles[3]
del Beatles[4]

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading