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

Python delete all elements from a list that are on an odd index

I’m trying to delete all elements from a Python list that are on an odd index of the list. In my case, the result from len(elements) is 40, so I assume after deleting all odd indexes, the total length should be 20. I tried the following code:

indx = 0
for element in elements:
   if indx % 2 == 1:
      elements.remove(element)
   indx += 1

After this, the result of len(elements) is 27, shouldn’t it be 20 since I deleted half of the elements?

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 :

It may be easier to just recreate the list with the indexes you want, e.g., by using a slice:

elements = elements[0::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