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

How to delete an element every 8 elements in a list of strings on python?

Suppose that you have a list of strings like the following one:

the_list = ['02:00', '  GBP', '', 'Construction Output (MoM) (Jan)', '1.1%', '0.5%', '2.0%', '',
            '02:00', '  GBP', '', 'U.K. Construction Output (YoY) (Jan)', '9.9%', '9.2%', '7.4%', '',
            '02:00', '  GBP', '', 'GDP (MoM)', '0.8%', '0.2%', '-0.2%', '',
            '02:00', '  GBP', '', 'GDP (YoY)', '10.0%', '9.3%', '6.0%', '',
            '02:00', '  GBP', '', 'Index of Services', '1.0%', ' ', '1.2%', '']

Which every 8 elements appears '', which is an empty string, and it happens to be the same empty string that exists next to the one called GBP

How could the_list variable be updated so that it deletes the '' element that appears every 8 elements in the array of strings?

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

>Solution :

If I understood you correctly, you can use list-comprehension to filter out the values at specific index:

new_list = [word for idx, word in enumerate(the_list, 1) if idx % 8 != 0]
print(new_list)

Prints:

['02:00', '  GBP', '', 'Construction Output (MoM) (Jan)', '1.1%', '0.5%', '2.0%',
 '02:00', '  GBP', '', 'U.K. Construction Output (YoY) (Jan)', '9.9%', '9.2%', '7.4%',
 '02:00', '  GBP', '', 'GDP (MoM)', '0.8%', '0.2%', '-0.2%',
 '02:00', '  GBP', '', 'GDP (YoY)', '10.0%', '9.3%', '6.0%',
 '02:00', '  GBP', '', 'Index of Services', '1.0%', ' ', '1.2%']
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