Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Additional condition in Python list comprehension

How would you delete all starting empty items form a list using list comprehension without deleting empty elements in the middle of list. This is an example:

desc = []
desc.append('')
desc.append('')
desc.append('')
desc.append('line 1')
desc.append('line 2')
desc.append('')
desc.append('')
desc.append('line 3')
filtered = [x for x in desc if x]
filtered
['line 1', 'line 2', 'line 3']

Here is a simple list comprehension that delete all empty items:

filtered = [x for x in desc if x != '']

What I am trying to achieve using list comprehension is something similar to this:

for i in enumerate(desc):
    if desc[0].strip() == '':
        desc.pop(0)
like image 225
bman Avatar asked Jun 14 '26 11:06

bman


2 Answers

Use itertools.dropwhile:

>>> from itertools import dropwhile

>>> lines = ['', '', 'line1', 'line2', '', '']
>>> list(dropwhile(lambda line: not line, lines))
['line1', 'line2', '', '']

Alternatively to the lambda, you could use operator.not_, as @JonClements suggests:

>>> from operator import not_

>>> list(dropwhile(not_, lines))
['line1', 'line2', '', '']
like image 169
Peter Wood Avatar answered Jun 16 '26 03:06

Peter Wood


Other solutions are good. If list comprehension is not necessary then maybe you can try this single line method,

>>> desc
['', '', '', 'line 1', 'line 2', '', '', 'line 3']
>>> 
>>> ';'.join(desc).lstrip(';').split(';')
['line 1', 'line 2', '', '', 'line 3']
>>> 

Step 1 - Join all elements of the list by some delimiter

>>> x = ';'.join(desc)
';;;line 1;line 2;;;line 3'

Step 2 - Strip delimiters from the starting of the string

>>> x = x.lstrip(';')
'line 1;line 2;;;line 3'

Step 3 - Split the string on delimiter to get the output

>>> x.split(';')
['line 1', 'line 2', '', '', 'line 3']
like image 40
Pankaj Parashar Avatar answered Jun 16 '26 04:06

Pankaj Parashar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!