Home > Back-end >  How to check for an element in the rest of a the list in python?
How to check for an element in the rest of a the list in python?

Time:09-11

My list goes like this:

[1,2,1,2,1,1,2,2,1]

I want to go through the list. Every time I find a 1 in the list, I want to look for the 2 that comes after it. If there's a 2, then I want to delete both the 1 and that particular 2. This process continues for all 1s in the list

At the end, here I should be left with the last 1, that's it

How do I do this using python?

CodePudding user response:

Simply translate your description into Python code:

>>> lst = [1,2,1,2,1,1,2,2,1]
>>> res = []
>>> for elem in lst:
...     if res and res[-1] == 1 and elem == 2:
...         res.pop()        
...     else:
...         res.append(elem)
...
>>> res
[1]
  • Related