Python Basics: Your First Steps Into Programming
For Loops
Lesson 10 of 16 • 10 XP
Keep your place in this quest
Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.
In this lesson, we’re going to learn about for loops and how to iterate over lists in Python.
A for loop is a structure that allows you to repeat a block of code for each item in a sequence, or for a certain number of times.
It’s especially useful when you need to perform an action multiple times and you either don’t know the exact number of repetitions ahead of time, or when that number comes from your data.
Basic Syntax
The basic structure of a for loop in Python looks like this:
for variable in sequence:
# code to execute for each item
Here’s what happens:
- Python goes through the
sequenceone item at a time. - The current item is stored in
variable. - The indented code block runs using that variable.
- Python moves to the next item, and repeats until there are no more items.
Iterating Over a List
Let’s start with a simple example:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
Output:
1
2
3
4
5
Here, numbers is a list, and number takes on each value from the list in order.
TIP: You can name the loop variable anything you like, but choose something descriptive for clarity.
Using range() to Generate Sequences
Python’s built-in range() function generates a sequence of numbers.
This is handy when you want to loop a certain number of times, or when you want to work with list indexes.
Example — using range() with list indexes:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i, "-", fruits[i])
Output:
0 - apple
1 - banana
2 - cherry
Here’s what’s happening:
len(fruits)returns the number of items in the list.range(len(fruits))creates a sequence from0up to (but not including) that number.itakes on each index, which we then use to accessfruits[i].
When to Use Each Approach
- Looping directly over items:
for fruit in fruits:
print(fruit)
✔ Cleaner and more readable if you only need the items.
- Looping over indexes with range():
for i in range(len(fruits)):
print(i, fruits[i])
✔ Useful when you also need the position of each item.
Wrapping Up
For loops are one of the most common tools you’ll use in Python. They let you: • Process every element in a list or string. • Repeat actions a certain number of times. • Work with both the position and value of items.
In the next lessons, we’ll combine for loops with other data structures to build more dynamic and interactive programs.