Victor Jeman - Frontend Architectv3.0
Python Fundamentals13 min

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:

python
for element in collection:
    # do something with element

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:

text
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:

text
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:

text
=== 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:

text
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:

text
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:

text
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:

text
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:

text
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:

text
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:

text
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:

text
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:

text
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():

python
list[start:stop:step]

Let's say you have the full week's schedule and you want to extract every other subject:

Result:

text
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:

text
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:

text
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:

text
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:

text
First subject alphabetically: Art
Last subject alphabetically: Physics

You can also use min() and max() directly with multiple values, without a list:

Result:

text
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

Create a list with 5 dungeon room descriptions (for example: "A dark room with torches on the walls", etc.). Use a for loop with range() to display each room with its number: "Room 1: [description]", "Room 2: [description]", etc.

Exercise : Treasure in each room

The hero traverses 5 dungeon rooms. In each room they find a quantity of gold: [10, 25, 5, 30, 15]. Use a for loop to iterate over the treasure list, add each sum to the hero's total gold (which starts at 50), and display a message for each room. At the end, display the total accumulated gold.

Exercise : Fight 3 monsters in a row

The hero must defeat 3 monsters in the dungeon. Create two parallel lists: monster_names = ["Goblin", "Skeleton", "Orc"] and monster_hps = [30, 40, 50]. The hero has attack = 20. Use a for loop with range() to iterate over each monster. For each one, calculate how many hits the hero needs (monster_hp // attack, +1 if there is a remainder) and display a message. At the end, display "The dungeon has been conquered!".

Exercise : End of dungeon report

After the hero finishes the dungeon, display a full report. You have the lists: rooms_explored = ["Entrance", "Hall of Columns", "Corridor", "Fountain", "Throne Room"], monsters_defeated = ["Goblin", "Skeleton", "Orc"], and gold_found = [10, 25, 5, 30, 15]. Display: (1) all explored rooms numbered, (2) all defeated monsters, (3) the total gold found (sum of the list, calculated with for), (4) the largest and smallest gold amount found (with max() and min()).

Exercise : Multiplication table

Write a program that generates the multiplication table for a number chosen by the user (from 1 to 10). Use a for loop with range(1, 11) to display each multiplication.

Example (for the number 7):

text
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70

Exercise : Bar chart with # characters

You have a list of values representing player scores: [8, 15, 5, 12, 20, 3] and a list with their names: ["Ana", "Mihai", "Ion", "Elena", "Radu", "Maria"]. Use a for loop to display a horizontal bar chart, where each bar is made of # characters (one # per point). Format the names to have the same spacing.

Example:

text
Ana   : ########
Mihai : ###############
...

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.

Question 1 of 5

What is the main difference between for and while?