[Fixed]-Django – 'pop index out of range' error when loop around multiple formset

1👍

By using pop you’re removing elements from the list:

>>> mylist = [0,1,2,3,4,5,6,7,8,9]
>>> for i in range(0, len(mylist)): 
...     print(mylist)
...     print(mylist.pop(i))
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2
[1, 3, 4, 5, 6, 7, 8, 9]
4
[1, 3, 5, 6, 7, 8, 9]
6
[1, 3, 5, 7, 8, 9]
8
[1, 3, 5, 7, 9]
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: pop index out of range

So children, which you’re using the length of, is constant, but childrenage_lst is constantly getting shorter and shorter. If you’re confident that the two will always start out being the same length, then just access elements in childrenage_lst using []:

for i in range(0, children):
    print(childrenage_lst[i])

That said, because of its initialisation, childrenage_str = '' and then childrenage_lst = childrenage_str, it looks like childrenage_lst is a string, which doesn’t have a pop method, so I think there’s something missing from the code you’ve posted, to get the TraceBack you’re getting.

Leave a comment