+ 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?

11th Apr 2019, 3:32 AM
Chen Zhang
Chen Zhang - avatar
5 odpowiedzi
+ 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
11th Apr 2019, 3:50 AM
Saksham Jain
Saksham Jain - avatar
+ 4
https://code.sololearn.com/c4buUZ9yCOB7/?ref=app
11th Apr 2019, 3:56 AM
Sarthak Pokhrel
Sarthak Pokhrel - avatar
+ 2
Chen Zhang Whichever answer helped you most mark it as correct answer by ticking the checkmark
11th Apr 2019, 1:55 PM
Saksham Jain
Saksham Jain - avatar
+ 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])
11th Apr 2019, 8:24 AM
Seb TheS
Seb TheS - avatar
+ 1
Thank you all! I understand this question now
11th Apr 2019, 12:53 PM
Chen Zhang
Chen Zhang - avatar