By the end of this tutorial, you will be able to write and use for loops in various scenarios.
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.
Term | Definition |
---|---|
For loop | An iterating function used to execute statements repeatedly. |
Iterate | In programming, iteration is the repetition of a code or a process until a specific condition is met. |
Iterables | Iterables are objects in Python that you can iterate over. |
Control flow | Control flow or program flow, is the order of execution in a program’s code. |
Control statements | In Python, continue, break, and pass are control statements that change the order of a program’s execution. |
Indentation | Indentation 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. |
Tuple | A tuple is an ordered set of values that is used to store multiple items in just one variable. |
if | if 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. |
else | The else statement contains the block of code that will execute if the condition from the if statement is false or resolves to zero. |
break | The break command terminates the loop that contains it and redirects the program flow to the following statement. |
continue | You can use the keyword continue to end a for loop’s current iteration and continue on to the next. |
pass | In Python, pass does nothing. It can be used as a placeholder or to disregard code. |
First, let’s examine the basic structure of a for loop in Python:
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.
Tell Python you want to create a for loop by starting the statement with for
.
1
for
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.
1
for kitten
Use the keyword in
.
1
for kitten in
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.
1
for kitten in box_of_kittens:
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.
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:
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)
1 2 3 4
numbers = [1,2,3,4,5,6,7,8,9,10] for num in numbers: print(num)
1 2
for num in range(1,11): print(num)
The flowchart below demonstrates the control flow in a Python for loop.
There are three main ways to break out of a for loop in Python:
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:
Does break work for nested loops?
Learn more: How to Use Python Break
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:
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:
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.
In this type of for loop, the character is the iterator variable and the string is the sequence variable.
Example:
1 2 3 4
# Write a for loop to iterate through a string and write it in reverse string = "Hello, World!" reversed_string = ""
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
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:
You can define your list and a tuple like this:
1 2
animals_list = ["cat", "dog", "giraffe", "elephant", "panda"] animals_tuple = ("cat", "dog", "giraffe", "elephant", "panda")
Then build your for loop:
1 2
for animal in animals_list: print(f"{animal}s are adorable!")
Run the code, and here's what you get:
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
1 2
for number in numbers: sum += number
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:
1 2 3 4
for iterator_1 in iterable_1: for iterator_2 in iterable_2: inner loop body outer loop body
Tip
Example:
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"]]
1 2 3
for sublist in main_list: for animal in sublist: print(animal)
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:
Learn more: How to Use Python If-Else Statements
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.
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.