planets=["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Urenus"]
for planet in planets:
print(planet)
del planets[0]
print(planets)
planet=planets.pop()
print(f"{planet} and {planets} and {len(planets)}")
Asked
Active
Viewed 40 times
0

David Buck
- 3,752
- 35
- 31
- 35
-
3Never modify a list when you're iterating over the list. It's always going to end in tears. – David Buck Jan 13 '21 at 13:30
-
Oh, Thank you, sir for your comment. But may I ask why is it not emptying the list? – Ravi Shankar Jan 13 '21 at 15:02
-
Have you looked at the question that is linked in the closure message above? The first answer does a good job of answering your question. – David Buck Jan 13 '21 at 17:34
1 Answers
1
I'm not sure the purpose of this code but for the list to be empty, how about:
planets=["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Urenus"]
while len(planets):
print(planet)
del planets[0]
print(planets)
if len(planets):
planet=planets.pop()
print(f"{planet} and {planets} and {len(planets)}")
which yields:
Jupiter
['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Urenus']
Urenus and ['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn'] and 5
Urenus
['Earth', 'Mars', 'Jupiter', 'Saturn']
Saturn and ['Earth', 'Mars', 'Jupiter'] and 3
Saturn
['Mars', 'Jupiter']
Jupiter and ['Mars'] and 1
Jupiter
[]
Kr.

antoine
- 662
- 4
- 10
-
I apologize if it is very absurd program in terms of programming, I am just a beginner finding out how things work in programming. And Thank you, sir for your interest to answer my question, so May I ask you, if it is not possible in for loop? – Ravi Shankar Jan 13 '21 at 15:01