0

I'm trying to remove some specific '' in the list using python.

The list is [1,'','',2,'','','',3,'']. I want to remove just one '' between two values. which means the output I want is [1,'',2,'','',3]. The code I had shows as below:

for j in range (len(lst)):
    if len(lst[j]) == 1:
        lst.remove(lst[j+1])
Andy
  • 3
  • 3

2 Answers2

1

Using itertools.groupby:

from itertools import groupby

l = [1,'','',2,'','','',3,'']

new_list = []
for v, g in groupby(l):
    new_list += list(g) if v != '' else list(g)[:-1]

print(new_list)

Prints:

[1, '', 2, '', '', 3]

Version 2 (one-liner with itertools.chain):

from itertools import groupby, chain

l = [1,'','',2,'','','',3,'']
new_list = [*chain.from_iterable(list(g) if v != '' else list(g)[:-1] for v, g in groupby(l))]
print(new_list)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

You can use the del operator. Just provide the index. del lst[1].

Ahmed
  • 120
  • 6