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.
>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.