Resolving looping gotchas

Now that we know what exactly are for-loops and how do they work in Python, we will end this article from where we began, that is, by trying to reason out looping gotchas as seen earlier.

Exhausting an iterator partially :

When we did :




numList = [0, 1, 2, 3, 4]
squares = (n**2 for n in numList)


and asked if 9 is in the squares, we got True. But asking again gives returns a False. This is because when we first asked if 9 is there, it iterates over the iterator(generator) to find 9 and we know that as soon as the next item in an iterator is reached, the previous item is deleted. This is why once we find 9, all the numbers before 9 get deleted and asking again returns False. Hence we have exhausted the iterator partially.

Exhausting an iterator completely :

In this code:




numList = [0, 2, 4, 6, 8]
doubles = (n * 2 for n in numList)


When we convert doubles to list, we are already iterating over each item in the iterator by doing so. Therefore, the iterator gets completely exhausted and finally, no items remain in it. This is why the function sum() on the tuple returns zero. If we do the sum without converting it into a list, it will return the correct output.



Understanding for-loop in Python

A Pythonic for-loop is very different from for-loops of other programming language. A for-loop in Python is used to loop over an iterator however in other languages, it is used to loop over a condition. In this article, we will take a deeper dive into Pythonic for-loop and witness the reason behind this dissimilarity. Let’s begin by familiarizing ourselves with the looping gotchas:

Similar Reads

Gotchas in for-loop

If one doesn’t know what “gotcha” means: a “gotcha” in coding is a term used for a feature of a programming language (say for-loop, function, return statement, etc) that is likely to play tricks by showing a behavior which doesn’t match the expected outcome. Here are two infamous for-loop gotchas:...

Resolving looping gotchas

...