2

Original intent was to create a "list pop" mechanism to yield values based on the size of the list; ie, a self-depleting list. Did not get expected behavior, but would like to know what is going on behind the scenes.

Did not see anything even remotely close to my problem, and perhaps there is already an answer, but I don't even know what category of question this is. Many of the suggested solutions offered by stackoverflow.com were irrelevant. Bug or feature?

>>> ab = []
>>> for i in range(10):
    ab.append(i)


>>> ab
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> def list_split(lst):
    ni = []
    for item in lst:
        ni.append(lst.pop(0))
    return ni

>>> ab
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> bc = list_split(ab)
>>> ab
[5, 6, 7, 8, 9]
>>> bc
[0, 1, 2, 3, 4]

What I had intended to happen was have ab spill its contents into bc, while keeping the order by forcing it to pop an item at index 0. As you can see, it apparently splits the list into two, giving the first half of the old list to the new list.

How does this have something to do with the indexing of the list, for a count of items in the list?

Ceegen
  • 21
  • 3
  • You shouldn't be removing elements from list while iterating over it. – Austin Jun 22 '19 at 03:16
  • Okay, thanks. The suggested answer "Why does Python skip elements when I modify a list while iterating over it?" answers some of my questions, but not all. Specifically, why popping at index of zero on every pass causes exactly only the first half of the list to be transmitted. Some of the answers indicate that some of indexes are skipped, but my "self-depleting list" mechanism was half-way successful, and seems like it can be manipulated to some computational benefit. – Ceegen Jun 22 '19 at 03:30
  • @Ceegen because half of the indices are removed before the internal iterator tries to index into `len(ab) / 2`, gets and index error, and the iteration stops. This entire approach is not recommendable to begin with, even if that result is your intent, because it would be an unecessarily inefficient way to accomplish that (O(N**2) when it can be done in O(N)) – juanpa.arrivillaga Jun 22 '19 at 03:57
  • i added another linked duplicate that has a particularly illustrative example, and you should be able to apply it to your particular case here – juanpa.arrivillaga Jun 22 '19 at 04:02

0 Answers0