+ 1
For and while
I need to remove all objects of a list. While will do that, but what about for? a=[1,2,3,4,5] while a: a.pop() print(a) —————- for i in a: a.remove(i) print(a) Why does the 2nd one not work?
5 ответов
+ 8
The second one doesn't work because for loop goes to next element of list...
Suppose a=[1,2,3,4,5]
On 1st iteration I is 0th element
And the list becomes[2,3,4,5]
on 2nd iteration it becomes 1st element means 3
And so on. .... Check the code
Better way to delete is del a[:]
https://code.sololearn.com/ckXcOI3WOeoA/?ref=app
+ 4
https://code.sololearn.com/c4buUZ9yCOB7/?ref=app
+ 2
Chen Zhang Whichever answer helped you most mark it as correct answer by ticking the checkmark
+ 1
You can remove items by for loops, but not strictly like you said, but by using:
for i in range(len(a)-1, -1, -1):
a.remove(a[i])
+ 1
Thank you all! I understand this question now