2
a=['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380']
for i in range(len(a)):
    if a[i]=="wdg":
        a.pop(i)
        print(a)

When I run these code, the error message shows" IndexError: list index out of range".(in line"if a[i]=="wdg":") What's wrong with it? I want to find all of the "wdg" in a list and delete it

Yiling Liu
  • 666
  • 1
  • 6
  • 21
  • I also struggled with the same lol :) and skipped many questions because of it. but then I read about 'List comprehension' and finally found the solution to the problem. – valkyrie55 Oct 04 '20 at 01:55

4 Answers4

3

Do not remove items from list while iterating through it. Every time, you pop from list, the length of list reduces by one. But you never account for this change in your loop. This causes list index out of range and stops your program abruptly.

A more secure and effective way is to use a list-comprehension like below:

a = ['abc', '234', 'wdg', '220', '400', '395', '230', '350', ' ', '300', '300', '340', '420', '190', '300', '380', '270', 'wdg', '350', '380']

a = [x for x in a if x != 'wdg']
Austin
  • 25,759
  • 4
  • 25
  • 48
2

To remove an element you can do:

 >>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print a
['a', 'c', 'd']

The error is occurring because you are iterating over a sequence of numbers - the original size of the list. Once the list shrinks, the index no longer exists. I would recommend iterating over the elements of the list like:

for elem in my_list:
    print(elem)

Instead of:

for i in len(range(my_list)):
   print(my_list[i])
Nick Tallant
  • 315
  • 3
  • 6
1

The list is getting shorter every time you pop an item, so by the time you get to the end, the index is longer than the length of the list. Try a list comprehension:

newList=[x for x in a if x!="wdg"]
user1763510
  • 1,070
  • 1
  • 15
  • 28
1

Since you measure the lenght of the list before the for loop, and you remove items during the for loop, your len(list) becomes wrong during iteration. That's why you run out of range. A simple way would be to iterate the list in reverse eg for i in reversed(range(len(mylist))). That way, when you are removing an element, it does not affect your remaining (previous) elements.

However, it would be better to use a list comprehension, as other users have pointed out.

blue_note
  • 27,712
  • 9
  • 72
  • 90