-2

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]
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 4
    It's not a good idea to modify a list while iterating over it. This fails on the last iteration because `i` will be `4` but since you deleted one item already your list will only have 4 items so the last index will be `3` – SitiSchu Sep 13 '22 at 13:16
  • I had not realized the situation, which "fails on the last iteration because it already removed an element out of 4, so the last index will be 3" – Miguel Angel Villa Sep 13 '22 at 14:03

1 Answers1

0

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']
CameL
  • 128
  • 4