Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove empty strings from a list except 1st one in Python

I am trying to remove empty strings from a list except the 1st element. I have this code –

my_list = ['', 'CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1', '']
while("" in my_list[1:]) :
  my_list.remove("")
print(my_list)

But I am not getting the desires result. It’s still removing the 1st element. The result I am looking for is –

['', 'CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1']

But I am getting –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1']

>Solution :

my_list = ['', 'CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1', '']
out = [el for i, el in enumerate(my_list) if i == 0 or el]
print(out)
['', 'CHANGE_TO(1)', 'x', 'x', 'x', 'x', 'x', '1']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading