From the course: Python Data Science Mistakes to Avoid

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Modifying a list while iterating over it

Modifying a list while iterating over it - Python Tutorial

From the course: Python Data Science Mistakes to Avoid

Start my 1-month free trial

Modifying a list while iterating over it

- [Instructor] Another common mistake in programming is modifying a list while iterating over it. To illustrate why this can be a problem as well as how to avoid this, I'll be walking you through an example. Let's say I created a list containing the items zero, one, two, three, four, and five, and saved it in a variable named nums. Also, I defined a function named is even, which takes in an integer as input and returns whether the given integer is even or not. For example, when is even as called on seven, false is returned. And when is even as called on eight, true is returned. Afterwards, I wrote a for loop that iterates over the items in the list nums. In each iteration, if the current item is even, it is deleted from nums. When the cell is run, I get an index error that says list index out of range. As I deleted items from the list while iterating over the list, there came a point where I had reached the end…

Contents