What happens when you try to delete a list item while iterating over it

I repeat the list as follows:

some_list = [1, 2, 3, 4]
another_list = [1, 2, 3, 4]

for idx, item in enumerate(some_list):
    del some_list[idx]

for item in another_list:
    another_list.remove(item)

When I print the contents of lists

>>> some_list
[2, 4]
>>> another_list
[2, 4]

I know that Python does not support modification listduring iteration over it, and the correct way is to iterate over a copy of the list (so please don't do the top-down). But I want to know what exactly is going on behind the scenes. Those. why the conclusion is above the fragment [2, 4]?

+4
source share
2 answers

You can use a makeshift iterator that shows (in this case prints) the state of the iterator:

class CustomIterator(object):
    def __init__(self, seq):
        self.seq = seq
        self.idx = 0

    def __iter__(self):
        return self

    def __next__(self):
        print('give next element:', self.idx)
        for idx, item in enumerate(self.seq):
            if idx == self.idx:
                print(idx, '--->', item)
            else:
                print(idx, '    ', item)
        try:
            nxtitem = self.seq[self.idx]
        except IndexError:
            raise StopIteration
        self.idx += 1
        return nxtitem

    next = __next__  # py2 compat

, :

some_list = [1, 2, 3, 4]

for idx, item in enumerate(CustomIterator(some_list)):
    del some_list[idx]

, :

give next element: 0
0 ---> 1
1      2
2      3
3      4
give next element: 1
0      2
1 ---> 3
2      4
give next element: 2
0      2
1      4

. .

+8

,

, ; , 0. , , , , , .

:

foo = ['a', 'b', 'c', 'd']
for index in range(len(foo)):
    del foo[index]

, foo == [], ? . 0, 1 0. 1, 2.

'a' 'c' *, 'b'. ( , , 2), 2 ; 0 1. , 2, . , : ['a', 'd'].

+1

Source: https://habr.com/ru/post/1684689/


All Articles