Delete items from the list with a specific item


Lets say we have a list [Y, X, 4, Y, 3, X, 2, X]

I want to be able to remove all elements that are immediately preceded by an X and also remove the X's themselves. So the result should look like [Y, Y, 3]. What would be the pythonic way of doing this?

I came up with something like the following, but I feel that it is very clunky and not clean. Is there a better way of doing this?

list = [Y, X, 4, Y, 3, X, 2, X]
is_preceded = False
result = []
for i in list:
    if i == 'X':
         is_preceded = True
    elif is_preceded == True:
         is_preceded = False

Using zip and list comprehension:

>>> lst = ['Y', 'X', 4, 'Y', 3, 'X', 2, 'X']
>>> [a for a, b in zip(lst, [''] + lst) if b != 'X' and a != 'X']
['Y', 'Y', 3]

# a: current item
# b: previous item

BTW, don't use list as a variable naem. It shadows builtin type/function list.

If you use Python 2.x, zip will return a new list. If you don't want it use itertools.izip.

In addition to that if you don't want to create temporary list ([''] + lst), you can use itertools.chain([''], lst).