How to Use For Loops in Python: Step by Step

Written by Coursera • Updated on

By the end of this tutorial, you will be able to write and use for loops in various scenarios.

[Featured image] Two coders work on using for loop in python on a monitor and a laptop.

Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), stable internet connection

Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts

For loops are control flow tools. They are used to iterate over objects or sequences—like lists, strings, and tuples. You may use a for loop whenever you have a block of code you want to execute repeatedly.

Glossary

TermDefinition
For loopAn iterating function used to execute statements repeatedly.
IterateIn programming, iteration is the repetition of a code or a process until a specific condition is met.
IterablesIterables are objects in Python that you can iterate over.
Control flowControl flow or program flow, is the order of execution in a program’s code.
Control statementsIn Python, continue, break, and pass are control statements that change the order of a program’s execution.
IndentationIndentation is the space at the beginning of each line of code. In Python, indentation indicates a new line of code. In other programming languages, it is used only for readability purposes.
TupleA tuple is an ordered set of values that is used to store multiple items in just one variable.
ifif is a common conditional statement. It dictates whether a statement should be executed or not by checking for a given condition. If the condition is true, the if block of code will be executed.
elseThe else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero.
breakThe break command terminates the loop that contains it and redirects the program flow to the following statement.
continueYou can use the keyword continue to end a for loop’s current iteration and continue on to the next.
passIn Python, pass does nothing. It can be used as a placeholder or to disregard code.

How to write a for loop in Python

First, let’s examine the basic structure of a for loop in Python:

Screenshot 2023-01-30 at 11.16.03 AM

for and in are both Python keywords, but you can name your iterator variable and iterable whatever you'd like. Remember to include a colon after your for loop statement, and indent code included in the body of the loop.

Now that we know the syntax, let’s write one.

Step 1

Tell Python you want to create a for loop by starting the statement with for.

PYTHON
1
for

Step 2

Write the iterator variable (or loop variable). The iterator takes on each value in an iterable (for example a list, tuple, or range) in a for loop one at a time during each iteration of the loop.

Example: Suppose you have a list called box_of_kittens [😾😺😼😽] as your iterable. You could name your iterator variable anything you want, but you might choose to call it 'kitten' to reference that you'll be looping through each individual kitten [😺] in box_of_kittens.

PYTHON
1
for kitten

Step 3

Use the keyword in.

PYTHON
1
for kitten in

Step 4

Add the iterable followed by a colon. The iterable (or sequence variable) is the object you will iterate through. In the example above where the loop variable is a kitten, the sequence variable is box_of_kittens because it represents the grouping the single variable is chosen from.

PYTHON
1
for kitten in box_of_kittens:

Step 5

Write your loop statements in an indented block. The indentation lets Python know which statements are inside the loop and which statements are outside the loop.

PYTHON
1
2
for kitten in box_of_kittens:
  print(f"{kitten} is such a cute kitten!")

Now let's run this code with a list called box_of_kittens and see what we get: Screenshot 2023-01-30 at 11.39.43 AM

Try it yourself

PYTHON
1
2
# Write a for loop that prints the numbers from 1 to 10, inclusive.
# (Hint: There's more than one way to do this)

PYTHON
1
2
3
4
numbers = [1,2,3,4,5,6,7,8,9,10]

for num in numbers:
  print(num)

PYTHON
1
2
for num in range(1,11):
  print(num)

How do for loops work in Python?

The flowchart below demonstrates the control flow in a Python for loop. -tutorial draft- for loop python

How to break out of a for loop in Python

There are three main ways to break out of a for loop in Python:

1. Break

The break keyword is used to exit a loop early when a certain condition is met. It terminates the loop that contains it and redirects the program flow to the next statement outside the loop.

Example: Screenshot 2023-01-30 at 12.15.04 PM

Does break work for nested loops?

In a nested loop, the break statement terminates only the innermost loop.

Learn more: How to Use Python Break

2. Continue

You can use the keyword continue to end the current iteration of a for loop. The control flow will continue on to the next iteration.

Example: Screenshot 2023-01-30 at 12.21.58 PM

3. Pass

The pass statement in Python intentionally does nothing. It can be used as a placeholder for future code or when a statement is required by syntax but you don’t want anything to happen.

In the context of a for loop, you can use a pass statement to disregard a conditional statement. The program will continue to run as if there were no conditional statement at all.

Example: Screenshot 2023-01-30 at 12.25.48 PM

Ways to use a for loop in Python

A for loop is a general, flexible method of iterating through an iterable object. Any object that can return one member of its group at a time is an iterable in Python. The sections below outline a few examples of for loop use cases.

Looping through a string to print individual characters

In this type of for loop, the character is the iterator variable and the string is the sequence variable.

Example: Screenshot 2023-01-30 at 12.30.11 PM

Try it yourself

PYTHON
1
2
3
4
# Write a for loop to iterate through a string and write it in reverse

string = "Hello, World!"
reversed_string = ""

PYTHON
1
2
for char in string:
  reversed_string = char + reversed_string

In this example, a for loop iterates through each character in the string string from beginning to end. For each character, it concatenates that character to the beginning of the variable reversed_string. By the end of the loop, reversed_string will contain the original string in reverse order.

Tip

If you want to print each character with an index value, you’ll need to use the range function. Learn more about the range function in How to Use Range: With Loops and Arguments.

Iterating over a list or tuple

When iterating over a list or tuple, the basic syntax of a for loop remains the same. However, instead of using a character and a string, you’d use your iterator variable to represent a single element and an iterable variable to represent the list or tuple it belongs to.

Example: Screenshot 2023-01-30 at 12.42.15 PM

You can define your list and a tuple like this:

PYTHON
1
2
animals_list = ["cat", "dog", "giraffe", "elephant", "panda"]
animals_tuple = ("cat", "dog", "giraffe", "elephant", "panda")

Then build your for loop:

PYTHON
1
2
for animal in animals_list:
    print(f"{animal}s are adorable!")

Run the code, and here's what you get: Screenshot 2023-01-30 at 12.49.02 PM

Try it yourself

PYTHON
1
2
3
4
# Write a for loop to iterate through a list and sum up the elements

numbers = [1, 2, 3, 4, 5]
sum = 0

PYTHON
1
2
for number in numbers:
  sum += number

Nesting for loops

A nested for loop is a loop inside of a loop. The innermost loop will execute once for each outer loop iteration. Here’s the structure of a nested for loop:

PYTHON
1
2
3
4
for iterator_1 in iterable_1:
  for iterator_2 in iterable_2:
    inner loop body
  outer loop body

Tip

Don’t forget—indentation is crucial in Python. Unlike other programming languages, Python relies on indentation to indicate blocks of code.

Example: Screenshot 2023-01-30 at 1.04.51 PM

Try it yourself

PYTHON
1
2
3
# Write a nested for loop to print out each element from each list within a list

main_list = [["cat", "dog", "giraffe"],["elephant", "panda","penguin"]]

PYTHON
1
2
3
for sublist in main_list:
  for animal in sublist:
      print(animal)

Using else block with python for loop

Else is a conditional statement that is used in combination with the if statement. In Python, you can also use it directly after the body of your for loop. Once all iterations are complete, the else block will be executed as part of the loop. The syntax of a for loop with an else block is as follows: Screenshot 2023-01-30 at 1.15.57 PM

Learn more: How to Use Python If-Else Statements

Key takeaways

  • For loops are used to iterate over objects or sequences.
  • Any object that can return one member of its group at a time is an iterable in Python.
  • There are three control statements you can use to break out of a for loop or skip an iteration in Python: break, continue, and pass.
  • Indentation tells Python which statements are inside or outside of the loop.

Resources

Keep improving your Python skills with Coursera.

You can practice working with for loops with a Guided Project like Concepts in Python: Loops, Functions, and Returns. Or, take the next step in mastering the Python language and earn a certificate from the University of Michigan in Python 3 programming.


Written by Coursera • Updated on

This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.

Learn without limits