Back to articles
The Secret Life of Python: The Loop That Skipped

The Secret Life of Python: The Loop That Skipped

via Dev.to PythonAaron Rose

Fixing Python’s skipped‑item bug when removing list elements Timothy scratched his head, staring at the console output. "Margaret, I think Python is lazy." Margaret looked up from her tea. "Python is many things, Timothy, but lazy isn't usually one of them. What makes you say that?" "I have a list of tasks," Timothy explained. "I wrote a loop to remove all the 'done' tasks. But it keeps missing some! It cleans up most of them, but leaves a few behind. It's like it's doing a half-hearted job." He showed her the code: # Timothy's Cleanup Script tasks = [ " done " , " todo " , " done " , " done " , " todo " ] print ( f " Start: { tasks } " ) for item in tasks : if item == " done " : tasks . remove ( item ) print ( f " End: { tasks } " ) Timothy ran it to prove his point. Output: Start: ['done', 'todo', 'done', 'done', 'todo'] End: ['todo', 'done', 'todo'] "See?" Timothy pointed at the screen. "It left a 'done' right in the middle! Why did it skip that one?" The Moving Floor Margaret smile

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
1 views

Related Articles