What is the output of this code snippet?
words = [‘cat’, ‘mouse’, ‘dog’]
for w in words[:]:
if len(w) > 3:
How to modify a sequence while iterating over it? For example, you want to prepare a data set of house prices for a machine learning algorithm to predict the market prices of new houses. Your goal is to remove the data points with prices lower than $20,000 to clean the data from outliers.
This problem is not as simple as removing elements from a sequence over which you iterate. Doing this can lead to unspecified behavior as explained in the following. Before entering the for loop, the Python interpreter creates an iterator object. The iterator object provides a method
next() returning the next element in the sequence. To achieve this, the iterator extracts, on creation time, information like the size of the sequence. If you modify the sequence “on the go”, this information becomes invalid.
For example, if the number of elements changes at runtime, the iterator object may believe it is ready, while there are still objects in it.
The puzzle presents one solution to this problem. The code copies the list first and iterates over the copy. With this method, we can safely modify the original list as this will not affect the copy in any way. The slice notation is a very convenient way to copy sequences.
Are you a master coder?
Test your skills now!