Delete list items by condition

There is a list of

lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]

You need to delete each element following 0

To get the output:

new_lst = [0,0,0,68,0,156,95]

The str.index() method doesn't help me, since it only returns the first match, and c enumerate doesn't work yet.

Author: MaxU, 2018-10-30

9 answers

Another solution:

res = lst[:1] + [b for a,b in zip(lst, lst[1:]) if a]

print(res)
# [0, 0, 0, 68, 0, 156, 95]

@AndreyNOP suggested a more concise and more elegant version:

res = [b for a,b in zip([1] + lst, lst) if a]
 7
Author: MaxU, 2018-11-02 08:24:45
lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]
# Поскольку перед первым элементом 
# нет ничего (и нуля в том числе, что соответствует условию), 
# то он добавляется в любом случае.
# К тому-же при i == 0, i - 1 == -1 исключения не будет,
# так-как элемент с индексом -1 присутствует в списке,
# это последний элемент списка 


# Через цикл

new_list = []
for i in range(len(lst)):
    if i == 0 or lst[i - 1] != 0:
        new_list.append(lst[i])
print(new_list)

# Через генератор

print([lst[i] for i in range(len(lst)) if i == 0 or lst[i - 1] != 0])
 6
Author: Ole Lukøje, 2018-10-30 23:57:30

Because of the crutch with the first element, I didn't want to write an answer, but I was wondering if someone could suggest a more elegant solution

from itertools import tee

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]
new_lst = [j for i, j in pairwise([None] + lst) if i != 0]
 3
Author: Sergey Gornostaev, 2018-10-31 07:46:25

Here is another solution, for the collection:

Update - wrapped in try to catch the StopIteration exception

lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]
seq = iter(lst)
newlst=[]
try:
    for _ in seq:
        newlst.append(_)
        if _==0:
            next(seq)
except StopIteration:
    pass
print(newlst)
 2
Author: strawdog, 2018-10-31 08:58:24

Python has a rich library, but there are not enough methods for processing consecutive pairs from iterable. Probably because there are many variations, and it is not clear how to put them all together. Three examples:

  1. Just pairs of [1, 2, 3] -> (1, 2), (2, 3)

  2. Cyclic pairs [1, 2, 3] -> (1, 2), (2, 3), (3, 1)

  3. Incomplete first pair [1, 2, 3] -> (None, 1), (1, 2), (2, 3)

There is still an incomplete last pair and what else comes to mind.

We need a third option. It is convenient that it works with any iterable, not only with a list:

def pairs(seq):
    prev = None
    for item in seq:
        yield prev, item
        prev = item

lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]

print([b for a, b in pairs(lst) if a != 0])
[0, 0, 0, 68, 0, 156, 95]
 2
Author: Stanislav Volodarskiy, 2021-01-02 15:02:20
lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]

def cut_after_zero(lst):
    index = 0
    while True:
        try:
            index = lst[:-1].index(0, index)
        except ValueError:
            return lst
        index += 1
        lst.pop(index)

print(cut_after_zero(lst))  # [0, 0, 0, 68, 0, 156, 95]
 1
Author: slippyk, 2018-10-31 08:23:39

Without libraries and iterators, with a forgotten loop while True:

lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]
zeros = 0
while True:
    try:
        zeros = lst.index(0,zeros)+1
        lst.pop(zeros)
    except:
        break

And also without creating new lists... )) Only the NAV saw that there is a similar solution. But-mine is clearer to me and shorter.

 1
Author: Vasyl Kolomiets, 2018-11-01 06:42:42
  1. you can use filter and map to remove unwanted items from the source list
lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]

# поиск индексов нужных элементов
delindex = list(filter(lambda i: lst[i-1]==0, range(1,len(lst)))) # здесь будут индексы удаляемых элементов

# удаление происходит в порядке от большего индекса к меньшему, для этого сортировка списка индексов
delindex.sort(reverse=True)

# удаление элементов
dellist = list(map(lambda d: lst.pop(d), delindex)) # здесь значения удалённых элементов

print(lst) # изменённый исходный список

With the help of the obtained secondary lists, you can restore the original one (if necessary, of course)

  1. or generate a new list using filter and map so
lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]

newindex = [0]+list(filter(lambda i: lst[i-1]!=0, range(1,len(lst))))
newlist = list(map(lambda n: lst[n], newindex))

print(newlist)
 0
Author: mr.polden2010, 2021-01-01 22:08:26

You can remember the sequential number of an item in the list, and work with it. For example like this:

list = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]
new_list = []

index = 0
for x in list:
    if list[index-1] != 0:
        new_list.append(x)
    index += 1

print(new_list)
 -1
Author: Виктор Шурига, 2018-10-30 22:42:21