1

While reading a list 'lst', I want to remove an delement that does not meet certain condition. Based on the following answer: Strange result when removing item from a list while iterating over it I found a solution that works great. Here is the code in PyCharm:

for ind, el in enumerate(lst):
    if not el.strip() or el.strip() != 'LABEL':
        lst[ind] = None #  here I get a warning concerning ind
    else:
        break
lst = [n for n in lst if n is not None]

I cannot figure out why I receive this warning:

Unexpected type(s): (int, None) Possible type(s): (SupportsIndex, str) (slice, Iterable[str]) 
Inspection info:
Reports type errors in function call expressions, targets, and return values. In a dynamically typed language, this is possible in a limited number of cases.
Types of function parameters can be specified in docstrings or in Python 3 function annotations.
drSlump
  • 33
  • 1
  • 6

2 Answers2

3

We don't see the rest of the code but you probably type-hinted your lst to have str elements only and None is not a str.

You don't have to implement a 2-pass algorithm to remove elements though. The following should be equivalent to your code, sans warnings (see docs for dropwhile):

from itertools import dropwhile

lst = list(dropwhile(lambda el: el.strip() != 'LABEL', lst))
Selcuk
  • 57,004
  • 12
  • 102
  • 110
-1

You can use list comprehension and do it all on one line. See the code below:

new_list = [x for x in lst if x.strip() != 'LABEL']

One more thing, I don't it is a good idea to modify a list while looping through it.

Daniel Afriyie
  • 217
  • 4
  • 12
  • This won't produce the same output as the OPs code (note the `break` statement in the original). Also, `I don't it is a good idea to modify a list while looping through it`: Why not? That's exactly what `list`s are for. That's why they are mutable while many other data structures in Python are not. – Selcuk Sep 17 '21 at 07:47
  • With modifying a list while looping through it you can read the answer that was given to the question the OP included in his question. Here is the link https://stackoverflow.com/a/6260097/11979729 – Daniel Afriyie Sep 17 '21 at 08:06
  • @DanielAfriyie Note the difference between "modifying" and "adding/deleting elements". Just editing or even replacing elements while you loop the list is usually fine. – tobias_k Sep 17 '21 at 09:40
  • @tobias_k Ok. I got it. – Daniel Afriyie Sep 17 '21 at 13:02