Home >Backend Development >Python Tutorial >Pitfalls in using for loop to delete elements in a list in python3
The following article will share with you a detailed discussion of the pitfalls of using a for loop to delete elements in a list in python3. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
The object of the for loop statement is an iterable object. The iterable object needs to implement the __iter__ or iter method and return an iterator. What is an iterator? Iterators only need to implement the __next__ or next method.
Now let’s verify why the list supports iteration:
x = [1,2,3] its = iter(x) # its = x.__iter__() print(type(its)) # print(its.__next__()) # print(its.__next__()) # print(its.__next__()) print(next(its)) print(next(its)) print(next(its))
Result:
<class 'list_iterator'> 1 2 3
How does the for statement loop? The steps are:
(1) First determine whether the object is an iterable object. If not, report an error directly and throw a TypeError exception. If so, call the __iter__ or iter method and return an The iterator
(2) continuously calls the __next__ or next method of the iterator, returning a value in the iterator in order each time
(3) iterates to the end, no updates If there are multiple elements, an exception StopIteration will be thrown. Python will handle this exception by itself and will not expose it to developers
list1 = [1,2,3,4,5,6] for i in list1: if i == 2: list1.remove(i) print(i) print(list1)
Result:
##
1 2 4 5 6 [1, 3, 4, 5, 6]
Pitfalls to pay attention to when deleting elements from python list
The above is the detailed content of Pitfalls in using for loop to delete elements in a list in python3. For more information, please follow other related articles on the PHP Chinese website!