In this tutorial, you’ll learn what a for loop is in Python, how it works, and how to use it in real programs. A for loop lets you repeat a block of code once for every item in a sequence, such as a list, a string, or a range of numbers.
The for loop is one of Python’s control flow statements, and it is one of the first tools you need to master when learning the basics of Python. By the end of this article, you will be comfortable looping over numbers, strings, lists, tuples, sets, and dictionaries, and you will know how to control a loop with break, continue, pass, and else.
Also, Solve:
Table of contents
- What is a for loop in Python
- for loop with range()
- How a for loop works
- Why use a for loop?
- If-else in a for loop
- Loop control statements in a for loop
- Else block in a for loop
- Reverse for loop
- Nested for loops
- for loop in one line
- Accessing the index in a for loop
- Iterate multiple lists in parallel using zip()
- Iterate a string using a for loop
- Iterate a list using a for loop
- Iterate a tuple and a set using a for loop
- Iterate a dictionary using a for loop
- Common mistakes and best practices
- Summary
What is a for loop in Python
In Python, a for loop is used to iterate over a sequence such as a list, string, or tuple, or over any other iterable object such as a range.
The loop picks up each item in the sequence, one at a time, and runs the same set of statements for it. This lets you automate repetitive tasks with just a few lines of code.
Unlike while loops, which keep running as long as a condition stays true, a for loop runs a fixed number of times: once for each item in the sequence. Here is a simple rule of thumb for choosing between them:
- Unknown number of repetitions: For example, asking the user to guess a lucky number. You don’t know how many attempts the user will need. It could be 1, 20, or more. In such cases, use a
whileloop. - Known number of repetitions: For example, printing the multiplication table of 2. You know you need exactly 10 iterations. In such cases, use a
forloop.

Syntax of a for loop
for item in iterable:
statement 1
statement 2
statement nCode language: Python (python)
forandinare keywords.itemis the loop variable. In each iteration, it holds the current value from the sequence. You can give it any valid variable name.iterableis the sequence you want to loop over, for example, a list, a string, orrange(). If a list contains 10 numbers, the loop runs 10 times.- The colon (
:) at the end of the first line is required, and the statements in the loop body must be indented (usually by 4 spaces). The indentation tells Python which lines belong to the loop.
Example: Print the first 10 numbers using a for loop
- We use the
range()function to generate integers from 0 to 9. - The
forloop iterates over the numbers produced byrange(). - In the loop body, we print the current number.
Output:
0 1 2 3 4 5 6 7 8 9
for loop with range()
The range() function returns a sequence of numbers. It is the most common way to tell a for loop how many times to run. It accepts up to three arguments:
range(start, stop, step)Code language: Python (python)
start(optional): The first number of the sequence. The default is 0.stop(required): The sequence stops before this number. The stop value itself is never included.step(optional): The difference between each number. The default is 1.
For example, range(5) produces 0, 1, 2, 3, 4. range(1, 6) produces 1 to 5, and range(0, 10, 3) produces 0, 3, 6, 9.

Example: Print the sum of all even numbers from 2 to 20
- Set a
totalvariable to zero. - Use
range(2, 21, 2)to get all even numbers from 2 to 20. Thestepvalue is 2, so every second number is skipped and only even numbers remain. - Use a
forloop to iterate over each number. - In each iteration, add the current number to
totalusing the arithmetic operator.
Tip: Avoid naming a variable sum, because that hides Python’s built-in sum() function. In fact, the whole example above can also be written as print(sum(range(2, 21, 2))).
How a for loop works
The for loop is the easiest way to perform the same action repeatedly. For example, suppose you want to calculate the square of each number in a list.
You write a for loop over the list. In each iteration, the loop takes the next number from the list, and inside the loop body you write the code that calculates the square of the current number.
Example: Calculate the square of each number in a list
Output:
Square of: 1 is: 1 Square of: 2 is: 4 Square of: 3 is: 9 Square of: 4 is: 16 Square of: 5 is: 25
Note:
The loop keeps running the statements in its body until it has processed the last element in the sequence. After the last element, the loop ends and Python moves on to the first line after the loop.

What happens behind the scenes
A for loop works with any iterable, which is any object that can hand out its items one at a time. Behind the scenes, Python does three things:
- It calls
iter()on the object to get an iterator. - It calls
next()on the iterator to get the next item and assigns it to the loop variable. - When there are no items left,
next()raises aStopIterationexception, and the loop ends quietly.
You can do the same steps by hand to see how it works:
This is why a for loop can iterate over lists, strings, tuples, sets, dictionaries, files, generators, and many other objects with the same simple syntax.
Why use a for loop?
Here are the main reasons to use a for loop in Python:
- Definite iteration: When you know how many times a loop should run, use a count-controlled loop such as a
forloop. This is known as definite iteration. For example, to calculate the percentage of 50 students, you know the loop must run 50 times (one iteration per student). - Less repetitive code: A loop repeats a block of code for you, so you don’t have to copy and paste the same lines again and again. This makes your code shorter, easier to read, and easier to change.
- Loop through sequences: You can iterate over lists, strings, tuples, dictionaries, and more, and perform operations on each item based on your own conditions.
Example: Calculate the average of a list of numbers
Output:
30.0
If-else in a for loop
In this section, you’ll see how to use if-else statements inside a loop. Use if-else when you want to do different things for different items. For example, print the names of students who scored more than 80 percent.
The if-else statement checks a condition. If the condition is True, Python runs the code inside the if block. If the condition is False, it runs the code inside the else block.
When you place an if-else statement inside a loop, Python checks the condition in every iteration and runs the matching block for the current item.
for item in iterable:
if condition:
block of statements
else:
block of statementsCode language: Python (python)
Example: Print all even and odd numbers from 1 to 10
- The
forloop iterates over the numbers from 1 to 10. - The
ifstatement checks whether the current number is even (divisible by 2 with no remainder). If it is, the program prints “Even Number”. Otherwise, theelseblock prints “Odd Number”.
Output:
Odd Number: 1 Even Number: 2 Odd Number: 3 Even Number: 4 Odd Number: 5 Even Number: 6 Odd Number: 7 Even Number: 8 Odd Number: 9 Even Number: 10
Practice Problem:
Use a for loop to print all numbers from 9 to 50 that are divisible by 2.
Show Solution
Loop control statements in a for loop
Loop control statements change the normal flow of a loop. Use them when you want to exit a loop early or skip part of it based on a condition. They are also known as transfer statements.
Python has three loop control statements: break, continue, and pass.
Break statement in a for loop
The break statement is used to terminate the loop immediately. Place break inside the loop, usually under an if condition, at the point where you want the loop to stop.
When Python reaches a break statement, it exits the current loop and continues with the first line of code after the loop.
Example: Break the loop if a number is greater than 15
- The
forloop iterates over each number in the list. - The
ifstatement checks whether the current number is greater than 15. If it is, the loop stops. Otherwise, the program prints the current number.
Output:
1 4 7 8 15
Note: If you use break inside a nested loop (a loop inside another loop), it stops only the innermost loop.
Continue statement in a for loop
The continue statement skips the rest of the current iteration and jumps straight to the next one.
In simple terms, when Python finds a continue statement inside the loop, it ignores the remaining code in the loop body for that item and moves on to the next item. Unlike break, it does not end the loop.
Example: Count the total number of ‘m’ characters in a string
- The
forloop iterates over each character of the string. - The
ifstatement checks whether the current character is ‘m’. If it isn’t,continueskips to the next character. If it is, the count increases by 1.
Output:
Total number of m is: 2
Note: In a nested loop, continue affects only the loop it is written in (the innermost one).
Pass statement in a for loop
The pass statement is a null statement: nothing happens when it runs. Python doesn’t allow an empty loop body, so pass is used as a placeholder when a block is required by the syntax but you don’t want to write any code there yet. It is also common in empty functions and classes.
This code runs without errors and produces no output. Without pass, Python would raise an IndentationError.
Else block in a for loop
Just like an if statement, a for loop in Python can have an optional else block. The else block runs only when the loop finishes normally, that is, after it has gone through every item.
The else block is skipped when the loop is stopped early by a break statement (or by an exception or a return).
Example 1: Else block in a for loop
In this example, we print the first 5 numbers. After the loop completes successfully, Python runs the else block.
Output:
1
2
3
4
5
Done
Example 2: Using both break and else
In this example, we print only the first two numbers out of five and then use break to stop the loop. Because the loop ends early, the else block does not run.
Output:
1
2
Example 3: A practical use of for-else: searching for an item
The else block is handy when you search for something. If the item is found, you break out of the loop. If the loop ends without finding it, the else block reports that it wasn’t found, with no extra flag variable needed.
Output:
8 not found in the list
Reverse for loop
So far, every loop has moved forward through a sequence. Sometimes you need to go backward instead, for example, to count down or to process a list from the last item to the first.
There are three ways to iterate backward with a for loop:
- Using the
reversed()function - Using
range()with a negative step - Using slicing (
[::-1])
Backward iteration using the reversed() function
The built-in reversed() function returns the items of a sequence in reverse order. It is the simplest and most readable way to loop backward, and it doesn’t create a copy of the list.
Output:
40 30 20 10
Reverse for loop using range()
You can also use range() with a negative step to count down. Remember that the stop value is not included, so to count down to 0 you must use -1 as the stop value.
Output:
Reverse numbers using for loop 5 4 3 2 1 0
Reverse for loop using slicing
The slice [::-1] creates a reversed copy of a list or string, which you can then loop over.
Output:
4 3 2 1
Nested for loops
A nested for loop is a for loop inside another for loop.
Nested loops are useful when you work with two-dimensional data, such as a table, a matrix, or a pattern of rows and columns. You can think of the outer loop as the rows and the inner loop as the columns.
For each iteration of the outer loop, the inner loop starts over and runs through all of its iterations. Only then does the next iteration of the outer loop begin.
Syntax of nested for loops:
# outer for loop
for element in sequence:
# inner for loop
for element in sequence:
body of inner for loop
body of outer for loop
other statementsCode language: Python (python)
Example: Use a nested for loop to print the following pattern
* * * * * * * * * * * * * * *

- The outer loop controls the number of rows. There are five rows, so the outer loop runs five times.
- The inner loop controls the number of columns (stars) in each row.
- In the first iteration of the outer loop, the inner loop runs once. In the second, it runs twice, and so on.
- In each iteration of the inner loop, we print one star.
end=" "keeps the stars on the same line. - After the inner loop finishes,
print('')moves to a new line for the next row.
While loop inside a for loop
A while loop is a condition-controlled loop, and a for loop is a count-controlled loop. You can mix them and place a while loop inside a for loop.
Example: Print the multiplication tables of the first 5 numbers using a for loop and a while loop
- The outer
forloop iterates over the first five numbers usingrange(). - In each iteration of the outer loop, the inner
whileloop prints the multiplication table of the current number.
Output (first two tables shown):
Multiplication table of: 1 1 2 3 4 5 6 7 8 9 10 Multiplication table of: 2 2 4 6 8 10 12 14 16 18 20 ...
for loop in one line
If the loop body is a single short statement, you can write the whole loop on one line:
This works, but it is usually clearer to keep the body on its own line. A more useful one-line form is a list comprehension, which builds a new list from a loop in a single expression.
new_list = [expression for item in iterable if condition]Code language: Python (python)
Example: Create a list of even numbers by adding 1 to each odd number in a list
Output:
[2, 6, 8, 10]
Accessing the index in a for loop
A plain for loop gives you only the values of a sequence. Sometimes you also need the position (index) of each item, for example, to number the items or to modify them in place. There are two common ways to do this.
Example 1: Print list items with their index using the enumerate() function
The built-in enumerate() function adds a counter to any iterable. In each iteration, it returns a pair: the index and the value. This is the recommended, most Pythonic approach.
Output:
numbers[ 0 ] = 4 numbers[ 1 ] = 2 numbers[ 2 ] = 5 numbers[ 3 ] = 7 numbers[ 4 ] = 8
By default, counting starts at 0. Use the start argument to begin from a different number:
Output:
1 apple 2 banana 3 cherry
Example 2: Print list items with their index using the range() function
Output:
Index: 0 Value: 1 Index: 1 Value: 2 Index: 2 Value: 4 Index: 3 Value: 6 Index: 4 Value: 8
Iterate multiple lists in parallel using zip()
When you have two or more related lists, the built-in zip() function lets you loop over them together. In each iteration, it gives you one item from each list. The loop stops when the shortest list runs out of items.
Output:
Jessa scored 85 Kelly scored 72 Emma scored 91
Iterate a string using a for loop
A string is a sequence of characters, so a for loop can go through it one character at a time. This makes many string operations simple. Let’s look at a few examples.
Example 1: Access all characters of a string
Output:
J e s s a
Example 2: Iterate a string in reverse order
Output:
a s s e J
Example 3: Iterate over a specific part of a string
The slice [2:7] selects the characters from index 2 up to (but not including) index 7.
Output:
s s a w
Example 4: Iterate over the words in a sentence using the split() method
Output:
Python makes loops easy to read
Iterate a list using a for loop
A Python list is an ordered collection of items, which can be of different data types. Each item has an index number, starting at 0 for the first item and ending at len(list) - 1 for the last. List items are written inside square brackets [].
Here are a few examples of Python lists:
There are several ways to loop through the items of a list. Here are the most common ones.
Example 1: Iterate over a list
Output:
2
3
5
6
7
Example 2: Iterate over a list using a for loop and range()
Output:
1
2
3
6
7
Example 3: Build a new list using a list comprehension
List comprehensions are the best choice when you want to create a new list from an existing one.
Output:
[1, 4, 9, 16, 25]
Iterate a tuple and a set using a for loop
You loop over a tuple in exactly the same way as a list. The items come out in their stored order.
Output:
red green blue
A set can be looped over too. Keep in mind that sets are unordered and contain no duplicates, so the order in which items are printed is not guaranteed.
Iterate a dictionary using a for loop
A Python dictionary stores data as key-value pairs inside curly braces {}. Each key must be unique. Here are some examples of dictionaries:
You can loop over a dictionary’s keys, its values, or both. Let’s see each option.
Example 1: Access only the keys of the dictionary
Looping over a dictionary directly gives you its keys.
Output:
Brand
Color
Date
Example 2: Iterate over the keys and values using items()
The items() method returns each key-value pair as a tuple, which you can unpack into two loop variables. This is the cleanest way to get both.
Output:
Brand -> BMW
Color -> Black
Date -> 1964
You can also get the value by its key inside the loop with dict1[key], but items() is shorter and faster.
Example 3: Iterate over only the values of the dictionary
Output:
BMW Black 1964
Common mistakes and best practices
Keep these points in mind to write cleaner loops and avoid common bugs.
1. Don’t modify a list while looping over it
Removing items from a list while you loop over it makes the loop skip elements. In the code below, the second 2 is never checked:
Instead, build a new list, or loop over a copy using numbers[:]:
2. The loop variable still exists after the loop
In Python, the loop variable keeps its last value after the loop ends. This can surprise you if you reuse the same name later.
3. Use _ when you don’t need the loop variable
If you only want to repeat something a few times and never use the loop variable, name it _. It tells other readers that the value is intentionally ignored.
4. Other quick tips
- Prefer
for item in my_listoverfor i in range(len(my_list)). Useenumerate()when you also need the index. - Don’t forget the colon (
:) at the end of theforline, and indent the loop body consistently. Missing either one causes aSyntaxErrororIndentationError. - Remember that
range(stop)never includesstop. To loop from 1 to 10, userange(1, 11). - Avoid variable names that hide built-in functions, such as
sum,list,max, orstr. - Use a list comprehension to build a new list, not to run code for its side effects. For example, write a normal loop to print items rather than
[print(i) for i in numbers].
Summary
- A
forloop runs a block of code once for each item in an iterable, such as a list, string, tuple, set, dictionary, orrange(). - Use
range(start, stop, step)to loop a fixed number of times. Thestopvalue is not included. breakexits the loop,continueskips to the next iteration, andpassdoes nothing and acts as a placeholder.- The optional
elseblock runs only if the loop finishes without hittingbreak. - Use
reversed(), a negativerange()step, or slicing to loop backward. - Use
enumerate()to get the index and value together,zip()to loop over several lists at once, anditems()to loop over dictionary keys and values. - Use list comprehensions to build new lists in one line.
Now put your knowledge to the test with the Python loop exercises and the Python loop quiz. To go further, read the guides on while loops, nested loops, and break, continue, and pass.
