< previous | Table of Contents | järgmine > |
8.7 COMMON ERRORS
INDEX ERRORS
Trying to access an index that is out of range for the list will raise an IndexError
. This often happens when looping over items. For example, when the range()
function input creates an iterable that extends beyond the number of elements in a list that you're iterating over.
Here's an example of how this would look like in Thonny.
REFERENCES AND COPIES
When you assign one list to another variable, both variables refer to the same list in memory. Changing the list using one variable will affect the other.
# Example of reference issue original = [1, 2, 3] copy = original copy.append(4) print(original) # Original is also changed to [1, 2, 3, 4] # To avoid this, create a copy original = [1, 2, 3] copy = original.copy() copy.append(4) print(original) # Original remains unchanged [1, 2, 3]
ISSUES DURING ITERATION
Modifying a list while iterating over it can lead to unexpected behavior and errors. In the example below the loop would keep on running indefinitely as the length of the elements list is increasing on every iteration and outpacing how quickly i
is incremented.
# Example of a possible infinite loop elements = [1, 2, 3] i = 0 while i < len(elements): elements.append(i) i += 1
< previous | Table of Contents | järgmine > |