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

pop index out of range: For Loop

list_ex1 = ['aaa', 'bbb', 'ccc', 111, 222, 333, 'Hello World']
list_ex2 = []

for i in range(len(list_ex1)):
    value = list_ex1.pop(i)
    list_ex2.append(value)

pop index out of range

>>> print(list_ex1)
['bbb', 111, 333]
>>> print(list_ex2)
['aaa', 'ccc', 222, 'Hello World']

I do not understand how can I pop all the values from list_ex1 using a for loop.

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 :

The iterator variable in your loop is going to go out of range because you are modifying the length of the list, therefore it cannot be used to access the list.
Instead of doing:

value = list_ex1.pop(i)

Do:

value = list_ex1.pop(0)

This will only pop the front item, once that front item is popped the next item becomes the new item at index 0, do this for the length of the list and each item in the list will be popped off.

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