0

Im getting an error for list index being out of range. Sorry if this is a stupid question.

def filter_list(l):
  for x in range(0, len(l)):
     if type(l[x]) is str:
       del l[x]
  return l
   
Yes
  • 25
  • 3

2 Answers2

0

When you use del to delete the item in the list, the list actually shortens and it seems like that is what is causing the problem.

If you would like to filter lists, you could use list comprehensions like so:

def filter(l):
    return [item for item in l if type(item) is not str]

Usually, when looping over lists, it is good practice not to delete or insert new items.

Hope this helped

Khoi-Viet Le
  • 20
  • 2
  • 3
0

You should not definitely change a list while iterating over it. It is very bad practise... it can lead to a whole lot of errors for you. Either you should create a copy of use something else, as list comprehension:

def filter_list(l):
    return [x for x in l if type(x) is not str]

print(filter_list([1, 4, 5, 's', 'demo'])) # Prints [1, 4, 5]
Shivam Jha
  • 3,160
  • 3
  • 22
  • 36