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)
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', '', '']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With