+ 1
mylist = [0, 1, 2, 3, 4, 5, 6, 7] for i in mylist: mylist.remove(i) print(myList) output is [1, 3, 5, 7] Why not removing all
Why it's not removing all members of the list.
5 Antworten
+ 6
When i=0, myList remove the item 0 of list and the result is [1,2,3,4,5,6,7].
The next step of i is the 2nd item of myList (2). myList removes 2 and the result is [1,3,4,5,6,7].
Next i is the third item of myList (4). myList removes 4 and the result is [1,3,4,6,7] and so on.
If you want to remove all elements of list, don't iterate over myList it self. This code will be remove all elements of myList
myList = [0,1,2,3,4,5,6,7]
for i in range(0,len(myList)):
myList.remove(i)
print(myList)
+ 4
You can use
myList=[1,2,3,4,5,6,7]
myList. clear()
Print(myList)
+ 3
To get rid of the index problem during iteration on a list, you can use something like this:
The task is, to remove all even numbers from a list, preserving the originlal sequnce of numbers:
#(1)
numbers = [4, 34, 16, 8, 11, 6, 4, 22, 14, 12, 2, 7]
for i in numbers[::-1]:
if i % 2 == 0:
numbers.remove(i)
print(numbers)
#(2)
numbers = [4, 34, 16, 8, 11, 6, 4, 22, 14, 12, 2, 7]
for i in numbers.copy():
if i % 2 == 0:
numbers.remove(i)
print(numbers)
#(3)
numbers = [4, 34, 16, 8, 11, 6, 4, 22, 14, 12, 2, 7]
numbers = [ i for i in numbers if i%2 != 0]
print(numbers)
+ 1
Rolando A. Rosales J. is absolutely on point.
Indeed, you should be careful: when iterating over a given iterable, you should in general avoid altering the size of that same iterable, because it will almost certainly lead to an undesirable behavior.
Note that changing the length of some iterables while iterating over them can raise an exception. That happens, for example, with sets and dictionaries, given that they use hash tables.
Happy coding!