O
8

Just figured out how to fix a common Python error at a weekend coding meetup

I was at a free coding meetup in Austin a couple weeks ago, working on a simple script to sort a list of names. I kept getting this 'list index out of range' error and I was stuck for like an hour. A guy sitting next to me, who was just there to learn too, leaned over and said, 'Hey, try printing the length of your list right before your loop.' I did it and saw my loop was trying to run one time too many. He explained that I was using 'len(names)' but my loop should go to 'len(names)-1'. It was such a simple fix, but I was so focused on the loop logic I missed the basic numbers. That one tip about checking the list size first saved me so much future headache. Has anyone else found a really basic check like that that solves a lot of errors?
2 comments

Log in to join the discussion

Log In
2 Comments
patking
patking14d ago
Printing each step like alex_taylor10 said can save your sanity for sure.
4
alex_taylor10
That's a classic one. When you're stuck on a loop error, do you find it helps more to print the index variable each step, or to check the list length right at the start like you did?
3