Search code examples
pythonlistenumerate

If item in list meets condition, remove item and multiple preceding items


I am looking for a way to remove every nth item (let's call that item i) in a list, and also x number of items directly preceding i in the list, if i meets a condition.

I have been looking around at list comprehensions and iterations but it has been tricky for a novice to find a solution.

Example:

myList = ["you", "are", "right", "I", "am", "wrong"]

For every 3rd item, check if i == "wrong": If so, remove i and the two (2) items preceding i.

Effect: The sequence "I, "am", "wrong" is deleted from the list.


Solution

  • >>> myList = ["you", "are", "right", "I", "am", "wrong"]
    >>> for i, l in enumerate(myList):
    ...   if l == 'wrong':
    ...     myList = myList[:i-2]
    ...     break
    ... 
    >>> myList
    ['you', 'are', 'right']
    

    Of course you could make 2 a variable