10
Just figured out why my loops kept breaking and it's so simple
I've been learning Python for about two months now, and I kept running into this weird bug where my for loops would stop early or skip items. Turns out, I was changing the list I was looping over inside the loop itself. Like, I'd have a list of numbers and try to remove some while the loop was still going through it. My mentor in a free online study group finally pointed it out last Tuesday. He said, 'You're editing the book while you're reading it.' The fix is to make a copy of the list first or loop over a copy. It seems obvious now, but it tripped me up for weeks. Has anyone else run into this specific loop problem when they were starting out?
3 comments
Log in to join the discussion
Log In3 Comments
lily702d ago
Oh man, editing the list while you loop it is a classic rite of passage. Did the same thing trying to clean up a list of usernames and just deleted half the class roster. Your mentor's book analogy is perfect, it's like tearing out pages as you go. That moment when you finally see it is equal parts relief and pure facepalm.
4
the_kim1d ago
Ugh, that book tearing image from lily70 is going to haunt me now. What gets me is how the mistake feels so obvious after, but your brain just locks onto the task of "remove bad thing" and ignores the wreckage. It's like your code is focused on the single step right in front of it and can't see the whole path anymore. Makes you wonder what other simple blind spots we all have right now, you know?
8
xenaf512d ago
Yeah that facepalm moment is so real. What finally clicked for me, lily70, was making a whole new empty list and only adding the items I wanted to keep while I looped through the original. It feels a bit silly at first, like extra work, but man it saves you from that panic. I mean it's basically just not messing with the thing you're actively reading from. Took me way too long to figure that one out honestly.
2