Python for Loop
Table of Contents + β
In the last lesson you learned the Ternary Operator. That was a short way to pick between two values on one line. It handled a single choice. Now we look at something different. We want to do the same job again and again. That is what a for loop is for.
π€ Why You Need a for Loop
Say you have a guest list and you want to print every name. Without a loop you would write the same print() line once for each guest.
Here is the painful way, by hand:
print("Alex")print("Riya")print("Arjun")print("Sara")That works for four names. But what if the list has forty names? Or four hundred? You would be copying that line forever. And if a new guest arrives, you have to add another line by hand.
A for loop fixes this. You write the printing step once. The loop runs it for every item in the list. The list can have four names or four thousand. Your code stays the same length.
π§© What a for Loop Is
A for loop repeats a block of code once for each item in a sequence. A sequence is just an ordered collection. It could be a list of names or the letters in a word.
Think of a teacher taking attendance. She has a list of students. She goes down the list and calls out one name, then the next, then the next, until the list ends. She does the same action for each student. She calls a name. A for loop is that same idea in code.
Here is the shape of it:
for item in sequence: # do something with itemLet me walk through that line:
forstarts the loop.itemis the loop variable. It holds one value from the sequence at a time.inconnects the variable to the sequence you want to walk through.sequenceis the thing you loop over, like a list or a string.- The colon
:at the end is required. It says βthe loop body starts nowβ. - The indented line below is the body. This is the code that runs once per item.
Caution
The colon at the end of the for line and the indentation of the body are not optional. Forget the colon and Python stops with a syntax error. Forget the indentation and Python does not know which lines belong to the loop.
π Looping Over a List
This is the most common use. You have a list and you want to touch every item in it.
Here we print each guest name from a list:
guests = ["Alex", "Riya", "Arjun", "Sara"]
for name in guests: print(name)Output
Alex Riya Arjun Sara
Now let me explain what happened, step by step:
- The loop variable here is
name. - On the first run,
nameholds"Alex", so it prints Alex. - On the second run,
nameholds"Riya", so it prints Riya. - This keeps going for each item in
guests. - When there are no more items, the loop stops on its own.
See how the print(name) line is written only once, but it ran four times? That is the whole point. The loop did the repeating for you.
You can do more than print. You can add a message around the value too:
guests = ["Alex", "Riya", "Arjun", "Sara"]
for name in guests: print(f"Welcome, {name}!")Output
Welcome, Alex! Welcome, Riya! Welcome, Arjun! Welcome, Sara!
π€ Looping Over a String
A string is also a sequence. It is a sequence of characters. So you can loop over a string the same way. The loop variable holds one letter at a time.
Here we print each letter of a word on its own line:
for letter in "CODE": print(letter)Output
C O D E
The loop variable letter held "C", then "O", then "D", then "E". Same idea as the list, just over characters instead of names.
π’ Looping a Fixed Number of Times with range()
Sometimes you do not have a list. You just want to do something a set number of times. Say you want to print βHelloβ five times. For that, Python gives you range().
range() produces a sequence of numbers, and the for loop walks over them. You never type the numbers out yourself.
Here we count from 0 to 4 by looping five times:
for i in range(5): print(i)Output
0 1 2 3 4
Notice two things. The numbers start at 0, not 1. And range(5) gives you five numbers: 0, 1, 2, 3, 4. It stops before 5. It does not include it. The loop variable here is usually called i, which is short for βindexβ.
Choosing where to start: range(start, stop)
If you do not want to start at 0, give range() a start value too. With two numbers, the first is where it starts and the second is where it stops. The stop is not included.
Here we count from 1 to 5, the way a person would count out loud:
for i in range(1, 6): print(i)Output
1 2 3 4 5
We wrote range(1, 6) because the loop starts at 1 and stops before 6. So the last number printed is 5.
Skipping with a step: range(start, stop, step)
You can also add a third number, called the step. The step is how much to jump each time. With no step, Python jumps by 1. Give it 2 and it counts every second number.
Here we print the even numbers from 0 up to but not including 10:
for i in range(0, 10, 2): print(i)Output
0 2 4 6 8
It started at 0, jumped by 2 each time, and stopped before 10. That is how you get 0, 2, 4, 6, 8.
Here is a quick table to keep the three forms straight:
| You write | You get | Plain meaning |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | Start at 0, stop before 5 |
range(1, 6) | 1, 2, 3, 4, 5 | Start at 1, stop before 6 |
range(0, 10, 2) | 0, 2, 4, 6, 8 | Start at 0, stop before 10, jump by 2 |
β οΈ Common Mistakes
A few things confuse almost everyone at the start. Watch for these.
Forgetting the colon at the end of the for line:
# β Avoid: no colon, Python stops with a syntax errorfor name in guests print(name)
# β
Good: colon at the endfor name in guests: print(name)Forgetting to indent the body, so Python does not know what belongs to the loop:
# β Avoid: body not indentedfor name in guests:print(name)
# β
Good: body indented under the for linefor name in guests: print(name)Expecting range(5) to include 5. It does not. The stop value is never reached:
# range(5) gives 0, 1, 2, 3, 4 β five numbers, but 5 is NOT one of themfor i in range(5): print(i)Looping over range() when you actually have a list. If you already have the items, loop over them directly. You do not need range() and index numbers to reach each one:
guests = ["Alex", "Riya", "Arjun"]
# β Avoid: extra steps to reach each namefor i in range(3): print(guests[i])
# β
Good: loop over the list itselffor name in guests: print(name)β Best Practices
- Name the loop variable for what it holds. Use
namefor a name,letterfor a letter,ionly when it is a plain counter. - Loop over the list or string directly when you have one. Reach for
range()only when you need numbers or a fixed count. - Keep the loop body small. If the steps inside grow long, move them into a function and call it from the loop.
- Remember that
range()stops before the stop value. When you want to count up to a number, set the stop one higher.
π§© What Youβve Learned
- β A for loop repeats a block of code once for each item in a sequence.
- β The loop variable holds one item at a time, and it changes on every pass.
- β You can loop over a list to touch each element, or over a string to touch each character.
- β
range()lets you repeat a fixed number of times, with optional start, stop, and step values. - β
The colon on the
forline and the indented body are both required.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does the loop variable hold during a for loop?
Why: On each pass the loop variable holds the next single item from the sequence.
- 2
What numbers does range(5) produce?
Why: range(5) starts at 0 and stops before 5, giving 0, 1, 2, 3, 4.
- 3
What does range(0, 10, 2) give you?
Why: It starts at 0, jumps by 2, and stops before 10, so you get 0, 2, 4, 6, 8.
- 4
Why does the for line need a colon and an indented body?
Why: The colon tells Python the body begins, and the indentation marks which lines are inside the loop.
π Whatβs Next?
You now know how to repeat code once for every item in a sequence. But what if you do not know how many times to loop? What if you only want to stop when some condition changes? That is the next tool.