Download Free Install Free

Python For Loops: Quick Answers and Examples

Anand Butani
By Anand Butani
March 25, 2019

Table of Contents

Learning about Python for loops

Much of the benefit we get from using computers is from programming them to do the same task multiple times in a row, which requires repeating the same block of code again and again.  This is where for each loops are useful in Python, or any other object-oriented programming (OOP) language. We will use for loop and for each loop interchangeably, as the Python for loop is always associated with some collection of items to which the each refers, and it is helpful to think about the items to be worked with. Officially, the Python documentation refers to the for loop as the “for statement.”

In this post, we’ll cover all of the basics about using loops in Python, specifically for loops, showing how they work and the different types of loops that can be used for various repetitive tasks.

What is a for loop?

Here is a technical definition of a loop: to iterate over items of any sequence such as a list or a string. In Python, iterative for-loops, or repeated executions of a block of code, are simply called a loop.  They are used for iterating over a dictionary, list, set, string, or tuple.

One thing you should make a distinction between is a while loop which is another primitive loop command within Python.  This command executes a set of statements as long as a condition is true.  For example, you may want to print something until a count reaches a specific number. This type of iteration is conditional and indefinite.

It will be easier to understand what a loop is, and where it will be beneficial after you have read through the examples given here in the next section:

Basic usage of for loops in Python

Often the best way to understand a language feature is to see it in action, and to have a template to refer back to. So, without further ado, here are a few examples. Feel free to get some practice by trying these with your Python interpreter, and optionally stepping through them with a debugger to see what the for loop is applied to at each step.

Looping through a string

We can refer to the elements of a string object, because it is iterable: a string consists of a sequence of characters, and that sequence is the finite collection of items we can supply to the for keyword.

Imagine we need to learn how many times a letter occurs in a word, or how many times a word occurs in a paragraph.  For example, if we need to figure out how many times “i” occurs in the word “Mississippi” –

>>> word = 'Mississippi'
>>> count = 0
>>> for letter in word:
>>> if letter == 'i':
>>> count = count + 1
>>> print(count)

4

Note: there are easier ways to count letters within a word through built-in tools such as ‘Mississippi’.count(‘i’)

Note the basic format here:

for <item> in <iterable>: 
	<Work to be done to item>

Any other statements within the for loop are followed by additional indentation, as in the if statement above. Also note that while the iterable must refer to (or be a declaration of) of an actual iterable, the item variable name can be whatever you want, as the contents change from one iteration to the next.

It is a good practice to name this something which clearly describes the type of element in the iterable. If brevity is desired, it is also acceptable to use a single letter, also preferably indicating the type of the object on which work is performed.

Caution (!) According to PEP8, never use lower-case “L” as a variable name, as this character is often indistinguishable from the number 1.

Looping through lists

The canonical situation where a loop will come in handy, is with a Python list.  Loops allow you iterate through the data and modify it however best suits your application. Note that the usage is exactly the same as above: start with an iterable, choose a variable by which to refer to individual items, then perform some operation using the item.

Say, you have a list of students and need to display the name of every student on that list –

>>> student_list= ("jake", "john", "jim")
>>> for student in student_list:
>>> print(student)

jake
john
jim

Note that, in this case, we are doing work while inside the loop, and not just adding up numbers. It’s important to remember that for loops are not just used for analysis, but also to perform repeated actions. This is why loops lay at the heart of programming, and are powerful tools to master.

How do loops work?

Let’s break this down a little bit and look at the specific steps carried out during a for loop. Sometimes loops become very complex, and it’s important to remember the fundamentals of what’s happening in the loop.

We will use a quick example to get each character in a string, where each aspect is defined, and the entire process is outlined:

>>> for character in "Kite":
>>> print(character)

K
i
t
e

In a Python loop the for and in are Python keywords; Kite is the string; and character is the loop variable that we assigned.

  1. We assign a loop variable “character”
  2. We define the iterable, which is “Kite”
  3. The loop pulls the first character and then prints it
  4. After that, the loop starts over again, (i.e. it takes the next element)
  5. It will print the next element and then start over
  6. The loop runs a total of 4 times, until no more elements are available

This pattern of processing is known as transversal. In Python, the loop is used to iterate over a sequence be it dictionaries, list, tuple, or sets – these are iterable objects.

Iterating the hard way

In the example below, we’ll create a tuple containing different water brands, and then use the iter() function to create an object that can be iterated through, also called an iterator.  Then we will use the next() function to call items one by one.

>>> example_tuple = ("smartwater", "fiji", "aquafina")
>>> my_tuple = iter(example_tuple)

>>> print(next(my_tuple))
>>> print(next(my_tuple))
>>> print(next(my_tuple))

smartwater
fiji
aquafina

How can we shorten this? You guessed it – a loop! We can use a for loop to iterate through the iterable object – the tuple (example_tuple). The for loop creates an iterator object and executes the next() method for each loop.

>>> example_tuple = ("smartwater", "fiji", "aquafina")

>>> for x in example_tuple:
>>> print(x)

As you can see, the for loop created an iterator object and essentially executed the next() method until the end of the list was reached with a lot less code to type!

Other for loop keywords and features

Much of the power of loops is found in special keywords that allow greater control over the basic iterative steps.

There are many things you can do within a loop to stop it after a certain point, skip over a certain sequence, conditions you can place, and you even put a loop within a loop. (This practice is called “nested” for loops, and is used when the iterable itself is nested–a list containing more lists, for example.)

First, we’ll cover the two different types of statements: break and continue. Then, we’ll cover the range() function, the else conditional, and nested loops.

The break statement

In a loop, you can stop a statement before it finishes looping through the remaining items. This is useful if the order of the list is known, or there is some specific place in the list where we want to stop doing work.

For example:

>>> students = ["John", "Jerry", "Sarah"]


>>> for x in students:
>>> print(x)
>>> if x == "Jerry":
>>> break

John
Jerry

If we want it to break after John, then we would put in the conditional and break before the print.

>>> students = ["John", "Jerry", "Sarah"]
>>> for x in students:
>>> if x == "Jerry":
>>> break
>>> print(x)

John

The break statement is also useful when you need to keep count of how many items you are printing. Think of a situation where you have only 5 spots on the bus, and you need a list of the first 5 students on the list–but not anyone else.

The continue statement

The continue statement is used to skip an iteration.  Let’s say we need to print that list from above, but Jerry is absent today. Or, in other words, to stop the current iteration and continue normally from the top.

>>> students = ["John", "Jerry", "Sarah"]
>>> for x in students:
>>> if x == "Jerry":
>>> continue
>>> print(x)

John
Sarah

The range() function

If you’re coming from another language, you may have noticed that Python for loops are much less formal, and don’t have as many associated parameters. Python fills in some of these blanks here with the range() function.

You can specify the number of times you want a set of code to be looped through by using the range() function.  This function will start from 0 by default and increment by 1 until the number that is specified.

>>> for x in range(5):
>>> print(x)

0
1
2
3
4

Keep in mind that these will produce the values 0 to 4 instead of 0 to 5.  Essentially, the count doesn’t include 5 and it will stop before it.

You can also specify the increment value as the third parameter with range(0, 10, 2).  Again, you will see the values stop before at 8 instead of at the end of the range 10.

>>> for x in range(0, 10, 2):
>>> print(x)

0
2
4
6
8

This can help you iterate through a list up to a specific count, or it can help you alternate between choices.  We aren’t covering all the features of the range() function here but I suggest reading up on it!

Perform work after the loop with else

The else keyword in a for loop will specify a block of code to execute when the loop is finished.  It can be used in many different ways such as requesting more data, if your loop is out of data, or if you have reached the end of a list.

>>> for x in range(5):
>>> print(x)
>>> else:
>>> print("Finally finished!")

0
1
2
3
4
Finally finished!

Nested loops

You can put loops within loops, sort of like the movie Inception. Nesting loops helps us deal with iterables living inside other iterables. This is one of two main reasons to place a for loop inside another for loop.

You can have lists within lists, where if you used one loop then it would print the individual lists.  Let’s take a look, and show you what would happen without a nested loop:

>>> list_of_lists = [['yorkshire', 'jack russell', 'golden retriever'],[0, 1, 2],[11, 22, 33]]

>>> for list_item in list_of_lists:
>>> print(list_item)

['yorkshire', 'jack russell’, 'golden retriever’]
[0, 1, 2]
[11, 22, 33]

Nesting a loop means we will execute another loop as part of the current iteration:

>>> list_of_lists = [['yorkshire', 'jack russell', 'golden retriever'],[0, 1, 2],[11, 22, 33]]

>>> for list_item in list_of_lists:
>>> for item in list_item:
>>> print(item)

yorkshire
jack russell
golden retriever
0
1
2
11
22
33

You see above we received all of the items individually instead of receiving 3 list iterators. While powerful, its easy for nested loops to become confusing, so try to keep a clear vision of what you mean to do rather than just using trial and error. There are many ways to iterate through collections, so you’ll be trying for a while!

The second major case for using nested loops is combining multiple lists, creating all possible permutations. Note that you will have to nest the list another level for every iterable, to get this behavior.

You can even combine two lists to create all of the permutations:

>>> adj = ["red", "sporty", "electric"]
>>> cars = ["BMW", "Lexus", "Tesla"]

>>> for x in adj:
>>> for y in cars:
>>> print(x, y)

red BMW
red Lexus
red Tesla
sporty BMW
sporty Lexus
sporty Tesla
electric BMW
electric Lexus
electric Tesla

Common for loop errors

As you start using Python more, you’ll start using loops in nearly every application, especially if your application has a lot of nested data.

Then as you start using nested loops, it is a a good idea to keep the code readable and avoid heavy nesting.  You don’t want to pile in too many iterator variables, because they are difficult to read, and error prone.

Infinite loop

The first problem will be an infinite loop, where a condition is always satisfied or never satisfied.

>>> count = 0
>>> i = 1
>>> while i == 1:
>>> count+=1

This is where you have to ensure that your condition will be false at a point or there is an endpoint eventually.

Incorrectly calling range()

When you want to print out numbers in a range, it prints out the first 5 numbers or in other words: 0, 1, 2, 3, and 4.

>>> for i in range(5):
>>> print(i)
0
1
2
3
4

Notice how “5” wasn’t included?  

This means if you want to print the number 5, you’ll have to go past that number and print anything in the range of 6.

>>> for i in range(6):
>>> print(i)
0
1
2
3
4
5

If you want to print only numbers, there are two different ways to do this:

The first way is by starting with the first number and the final number plus 1:

>>> for i in range(1, 6):
>>> print(i)
1
2
3
4
5

The second way is to adjust the print from only printing i to printing i + 1 (1 through 5).

>>> for i in range(5):
>>> print(i+1)
1
2
3
4
5

Advanced for loop use cases

Blogs

Within a blog, we can use a loop to showcase a list of all of the blog posts, or maybe even just certain ones.  If your blog posts have tags, then you can set a filter to display only the blog posts with that specific tag.

eCommerce

On an eCommerce website, a loop can be used to change the price displayed to visitors by a certain amount or percentage without altering the original price in the database. This can be beneficial if your database holds the cost of the product but the eCommerce software needs to add a markup to all items of 20% for the profit margin, this is then what is displayed to the potential buyer as the final price.

Newsfeeds

Most people have used Facebook and will know about the newsfeed: the place where you see posts from your friends, pages, and the groups that you follow.  A loop can be used to showcase posts from friends you are connected with or filtered to show posts within a specific time range.

You can even use a nested loop (which we will cover below) to show certain posts sooner based on how many mutual friends liked that post. Note that in each of these cases we still had some object living in a collection on which we needed to perform work. Even in complex cases, the fundamentals are the same.

Next steps

In addition to the ideas above, get in the habit of looking for ways to iterate through collections in your code. For example, one thing we didn’t cover was how specifically to iterate through dictionaries. Since dictionaries have various methods to return iterables, there are quite a few ways to iterate through dictionaries, but don’t take my word for it!

After that I would suggest looking at ways you can write for loops to sound even more like human language. The greatest advantage to Python is that it is so readable, you can more easily “think” in Python than other languages, and just write your ideas down as code.

Try to make your for loops look and sound like they would in human language, and you’ll spend less time having to think about how they work.

The last component to your for loop learning would be understanding the optimizations that can be applied to for loops to increase times and reduce memory loads.