Understanding for-loop in Python
Last Updated :
29 Dec, 2019
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:
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:
Consider this example:
Python3 1==
numList = [0, 1, 2, 3, 4]
squares = (n**2 for n in numList)
Here, the variable
squares
contains an iterable of squares of the elements of
numList
. If we check whether 16 is in
squares
, we get True but if we check it again, we get False.
sum of a for-loop :
Take a look at this:
Python3 1==
numList = [0, 2, 4, 6, 8]
doubles = (n * 2 for n in numList)
We can make this
doubles
into a list or tuple to look at its elements. Let's calculate the sum of the elements in doubles. The result should be 40 as per expectation.
But, we get 0 instead.

To understand this anomaly, let's first see "under-the-hood" working of for-loops.
Inside a for-loop
As stated earlier, for-loops of other programming languages, such as C, C++, Java, loop over a condition. For example:
javascript
let numList = [0, 1, 2, 3, 4];
for (let i = 0; i < numList.length; i += 1) {
print(numList[i])
}
The above code is written in Javascript. As seen the for-loop is quite different from what we see in Python. This is because what we call a for-loop in Python is actually a "
foreach" loop. A foreach loop doesn't maintain a counter like a for loop. A for loop works on indices of the elements of the iterable rather than the element itself. But a foreach loop works straight on the elements rather than their indices and thus have no conditions, no initializations and no incrementation of index.
Python3 1==
numList = [0, 1, 2, 3, 4]
# for loop in Python
for n in numList:
print(n)
Hence, it won't be wrong to say that we don't have for-loops in Python but we have foreach loops which are implemented as for-loops!
One might think that Python uses indices under the hood to loop over in a for loop. But the answer is no. Let's look at an example to prove this:
We will take the help of while loop for using indices.
CPP
games = { 'tennis', 'baseball', 'rugby', 'soccer' }
i = 0
while i < len(games):
print(games[i])
i += 1
Output:

This proves that Python doesn't make use of indices for looping and so we can't loop over everything using indices. A simple question now arises, what does Python use for looping? The answer is, iterators!
Iterators
We know what iterables are(lists, strings, tuples, etc). An iterator can be considered as the power supply of iterables. An iterable is made up of iterator and this is the fact which helps Python to loop over an iterable. To extractor iterator from an iterable, we use Python's
iter
function.

Let's look at an example:
Python3 1==
games = ['tennis', 'baseball', 'rugby', 'soccer']
iterator = iter(games)
# we use the next() function to
# print the next item of iterable
print(next(iterator))
print(next(iterator))
print(next(iterator))
If we keep on using the
next()
function even after we reach the last item, we will get a StopIteration Error.
Note: Once an item in an iterator is all used up(iterated over), it is deleted from the memory!

Now that we know how loops work, let's try and make our own loop using the power of iterators.
Python3 1==
# Python program to demonstrate
# power of iterators
# creating our own loop
def newForLoop(iterable):
# extracting iterator out of iterable
iterator = iter(iterable)
# condition to check if looping is done
loopingFinished = False
while not loopingFinished:
try:
nextItem = next(iterator)
except StopIteration:
loopingFinished = True
else:
print(nextItem)
# Driver's code
newForLoop([1, 2, 3, 4])
Output:
1
2
3
4
We need to learn about iterators because we work with iterators almost every time with even knowing about it. The most common example is a generator. A generator is an iterator. We can apply each and every function of an iterator to a generator.
Python3 1==
numList = [0, 2, 4]
# creating a generator named "squares"
squares = (n**2 for n in numList)
print(next(squares))
print(next(squares))
print(next(squares))
Output:
0
4
16
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 :
Python3 1==
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:
Python3 1==
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.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read