# For loops

By Martin McBride, 2022-09-15
Tags: for loop list iterator generator list comprehension
Categories: python language intermediate python

You will probably have met for loops in conjunction with the range function, in simple code like this:

for i in range(5):
print(i)


This code prints values 0, 1, 2, 3, and 4. It is more or less the Python equivalent of the following C or Java style loop:

for (i = 0; i < 5; i++)
{
print(i);
}


In fact, in Python, loop indices (the variable i) are not used all that often - it might even be considered un-Pythonic. Usually for loops are used to loop directly over a list or other sequence of values.

## Pythonic for loops

In this tutorial, we will look at various other techniques available in Python to make your loops shorter and easier to read. The techniques we will cover are:

We can use these techniques to loop over sequences of different types, such as:

• Lists.
• Tuples.
• Strings (character by character).
• Sets.
• Dictionaries.

We can also loop over iterables and generators.