For loops and range()
Learn to iterate over lists and sequences with for and generate numbers with range().
What You'll Learn
- Use the for loop to iterate over lists and strings
- Generate number sequences with range()
- Insert elements into lists with insert()
- Use advanced slicing with step and the min()/max() functions
So far you have used while to repeat things. It worked, but it was a bit like manually counting every student in the register, you go line by line and stop when you reach the end. The for loop is the more elegant version: you tell it "take each element from this collection and do something with it" and Python handles the rest. No counting, no checking conditions, no incrementing counters.
Think of the difference like this: while is for situations where you do not know exactly when to stop (waiting for user input, for example). for is for situations where you know precisely what you are iterating over, a list of subjects, a set of grades, a weekly timetable. And that is exactly what we will do in this lesson: we will build a school schedule generator, piece by piece.
The dungeon has multiple rooms, and the hero must explore them all. In this lesson you add dungeon exploration with multiple rooms, using for loops and range(). The hero will traverse a series of rooms, find treasures, and fight multiple monsters in a row.
The for loop
The basic structure of a for loop is simple and straightforward:
for element in collection:
# do something with element
pass
The word element is a variable that takes on the value of each element in the collection, one at a time. You can name it anything you want. Python does not force a particular name. What matters is that the name makes sense in context.
Let's start with a simple example. You have a list of school days and you want to display each one:
Result:
Today is: Monday
Today is: Tuesday
Today is: Wednesday
Today is: Thursday
Today is: Friday
At each iteration (pass through the loop), the variable day receives the next value from the list. The first time it is "Monday", then "Tuesday", and so on until "Friday". When the list ends, the loop stops automatically. You do not need any counter or stopping condition.
You can also use for on a string. Python treats it as a collection of characters:
Result:
M
A
T
H
Iterating over lists
Now let's move on to something more practical. Imagine you have a list of Monday's subjects and you want to display them numbered, like in a real timetable. You can use for together with a counter variable:
Result:
=== Monday Schedule ===
Period 1 - English
Period 2 - Mathematics
Period 3 - Physics
Period 4 - History
Period 5 - PE
We go through each subject in the list and, at the same time, keep a counter that increases by 1 at each step. Simple and clean.
You can combine for with if to filter elements. Let's say you want to see only the subjects that start with the letter "M":
Result:
Subjects starting with M:
- Mathematics
- Music
- Media Studies
The range() function
The for loop does not only work with lists. You can give it any sequence, and range() is the function that generates sequences of numbers. When you give it a single parameter, it generates numbers from 0 up to that number (without including it):
Result:
Class period: 0
Class period: 1
Class period: 2
Class period: 3
Class period: 4
Class period: 5
range(6) generates the numbers 0, 1, 2, 3, 4, 5. Six numbers in total, starting from 0. The last number (6) is not included, exactly like slicing.
This is very useful when you want to repeat something an exact number of times:
Result:
Generating schedule for Year 7
Generating schedule for Year 8
Generating schedule for Year 9
Generating schedule for Year 10
Generating schedule for Year 11
We added + 7 to year so that we start from Year 7 instead of Year 0. But there is a more elegant way to do this, with two parameters.
range() with two parameters
When you give range() two values, the first is the starting point and the second is the limit (excluded):
Result:
Period 1
Period 2
Period 3
Period 4
Period 5
Period 6
range(1, 7) generates: 1, 2, 3, 4, 5, 6. It starts at 1 and stops before 7. Much clearer than manually adding +1 everywhere.
Let's use this to generate a schedule with classroom numbers:
Result:
Prof. Johnson - Room 100
Prof. Smith - Room 101
Prof. Williams - Room 102
Prof. Brown - Room 103
Prof. Davis - Room 104
Here we used i as an index both to access elements from the teacher list and to calculate the room number.
range() with three parameters (step)
The third parameter of range() is the step, how much to jump between numbers. By default, the step is 1, but you can change it:
Result:
Long breaks after periods:
- After period 1
- After period 3
- After period 5
range(1, 7, 2) generates: 1, 3, 5. It starts at 1, jumps by 2, and stops before 7.
You can also use a negative step to count backwards. This is useful when you want to display a countdown:
Result:
Class starts in:
5 ...
4 ...
3 ...
2 ...
1 ...
Off to class!
range(5, 0, -1) generates: 5, 4, 3, 2, 1. It starts at 5, decreases by 1, and stops before 0.
The insert() method
You already know that you can add elements to the end of a list with append(). But what do you do when you want to add an element at a specific position? You use insert().
insert() takes two parameters: the index where you want to place the element and the element itself. All elements after that index shift one position to the right:
Result:
Original schedule: ['Mathematics', 'Physics', 'English', 'History']
Updated schedule: ['Mathematics', 'Assembly', 'Physics', 'English', 'History']
"Assembly" was inserted at position 1 (the second position, because indexing starts at 0). "Physics", "English", and "History" each shifted one position to the right.
If you want to insert at the beginning of the list, use index 0:
Result:
Thursday schedule: ['PE', 'Chemistry', 'Biology', 'History', 'Geography']
Advanced slicing (with step)
You have already learned how to extract portions of lists with slicing (list[start:stop]). But slicing also accepts a third parameter, the step, just like range():
list[start:stop:step]
Let's say you have the full week's schedule and you want to extract every other subject:
Result:
Every 2nd subject: ['Math', 'Physics', 'Biology', 'Art', 'Computer Science']
[::2] means: from the beginning to the end, with a step of 2. So it takes the elements at positions 0, 2, 4, 6, 8.
A very useful trick is to reverse a list using a step of -1:
Result:
Week from the end: ['Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday']
You can combine all three parameters. Let's say you want the subjects at positions 1, 3, 5 (the second, fourth, and sixth):
Result:
Periods at odd positions: ['English', 'Chemistry', 'History']
The min() and max() functions
When working with lists of numbers, you often want to find the smallest or largest value. Python gives you two simple functions for that: min() and max().
Result:
Math grades: [7, 9, 5, 10, 8, 6]
Lowest grade: 5
Highest grade: 10
The min() and max() functions also work with strings. In that case they compare alphabetically:
Result:
First subject alphabetically: Art
Last subject alphabetically: Physics
You can also use min() and max() directly with multiple values, without a list:
Result:
Best test grade: 9
Worst test grade: 6
The for loop automatically iterates over each element in a collection (list, string, or range). The range() function generates sequences of numbers with 1, 2, or 3 parameters (stop, start/stop, start/stop/step). The insert() method adds elements at any position in a list, slicing with step extracts elements at regular intervals, and min() and max() find the extremes in a collection.
Exercise : Dungeon with 5 rooms
Exercise : Treasure in each room
Exercise : Fight 3 monsters in a row
Exercise : End of dungeon report
Exercise : Multiplication table
Exercise : Bar chart with # characters
Complete game code: Python Kingdom (Lesson 7)
Your game now has a dungeon with multiple rooms! The hero explores room by room, fighting monsters and finding treasures:
Test Your Knowledge
Check how well you understood the lesson with these 5 questions.

