Python for Loops & range()Get Certified
What Is a for Loop?
A loop repeats a block of code. Instead of writing the same instruction ten times, you write it once and let Python run it ten times. A for loop is the loop you use when you want to go through the items of a collection one at a time, or to repeat something a known number of times. Python’s for loop is different from the counting loop of languages such as C or Java: it does not count with a variable that you update yourself. It takes an iterable, such as a list, a string, or a range(), and hands you its items one by one.
- Syntax:
for item in iterable:followed by an indented block. - Iterables: lists, tuples, strings, dictionaries, sets, and
range()can all be looped over. range(): produces a sequence of numbers to repeat an action a fixed number of times.- Helpers:
enumerate(),zip(),reversed(), andsorted()make loops shorter and clearer. - Control:
breakstops a loop,continueskips to the next item, andelseruns when the loop was not stopped. - Nested loops: a loop inside a loop works through rows and columns.
Looping Over a List
The basic form is for variable in collection:. On each repetition Python assigns the next item to the loop variable and runs the indented block once. When the items are used up, the loop ends and the program continues with the first line that is not indented. You can choose any name for the loop variable, and a good name describes one item, such as fruit for a list called fruits.
Try It: Your First for Loop
Click Test My Code. Then add a fourth fruit to the list and run it again.
for loop. The last line is not indented, so it runs once after the loop has finished.fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
print("Done")fruits refers to a list that holds three strings.fruit. The colon opens the loop body.fruit is "apple", then "banana", then "cherry". The output is three lines: apple, banana, and cherry.Done.Looping Over Strings, Tuples, and Dictionaries
Anything that is iterable can follow the word in. A string gives its characters one by one, and a tuple or set gives its items like a list. A dictionary gives its keys by default. To get the values use .values(), and to get keys and values together use .items(), which produces pairs that you can unpack into two loop variables.
Try It: Strings and Dictionaries
Click Test My Code. Notice how the two dictionary loops give the same information in two different ways.
items().for letter in "Hi!":
print(letter)
prices = {"tea": 3, "coffee": 5}
for item in prices:
print(item, prices[item])
for item, price in prices.items():
print(f"{item} costs {price}")letter becomes "H", then "i", then "!".H, i, and !.prices refers to a dictionary with two keys, "tea" and "coffee".item is "tea" and then "coffee".prices[item] finds the value that belongs to the key. The output is tea 3 and coffee 5.items() gives each entry as a pair. The loop unpacks every pair into the two variables item and price.tea costs 3 and coffee costs 5.The range() Function
To repeat something a number of times, or to work with numbers, use range(). It produces a sequence of integers and comes in three forms:
range(stop)counts from0up to, but not including,stop. Sorange(5)gives 0, 1, 2, 3, 4.range(start, stop)begins atstart, as inrange(2, 8).range(start, stop, step)moves bystep. A negative step counts down.
A range does not store all its numbers. It calculates each one when needed, so range(1000000) uses almost no memory. Use list() to see the numbers it would produce. The arguments must be integers. For decimal steps, calculate the values inside the loop.
Try It: What range() Produces
Click Test My Code. Predict each line before you look at the output, especially the one that counts down.
print(list(range(5)))
print(list(range(2, 8)))
print(list(range(0, 20, 5)))
print(list(range(10, 0, -3)))
print(len(range(100)), 3 in range(5))range(5) starts at 0 and stops before 5. The output is [0, 1, 2, 3, 4].[2, 3, 4, 5, 6, 7].[0, 5, 10, 15].[10, 7, 4, 1].len(range(100)) is 100, and 3 in range(5) is True because 3 is one of the numbers 0 to 4. The output is 100 True.Counting and Accumulating
A very common pattern is to create a variable before the loop and update it inside the loop. This is called an accumulator. Use a number to build a total or a count, a list to collect results, or a string to build text. If you do not need the loop variable, the convention is to name it _, as in for _ in range(3):. The loop variable also stays available after the loop and keeps the value of the last item.
Try It: A Running Total
Click Test My Code. Change range(1, 6) to range(1, 11) and predict the final sum before you run it.
i and the running total. After the loop it prints the final sum.total = 0
for i in range(1, 6):
total += i
print(f"i = {i}, total = {total}")
print("Sum:", total)total starts at 0. It is created before the loop, so that it is not reset on every repetition.range(1, 6) gives 1, 2, 3, 4, and 5. The stop value 6 is not included.total += i is short for total = total + i. The total becomes 1, then 3, 6, 10, and 15.i = 1, total = 1 to i = 5, total = 15.Sum: 15.enumerate(), zip(), and reversed()
Python provides several built-in helper functions that make working with loops easier, faster, and more efficient. Functions like range(), enumerate(), and zip() help you iterate over sequences, access index values, and process multiple collections without manually managing counters. These tools make your code cleaner, shorter, and less prone to errors.
enumerate(items, start=0)gives pairs of a counter and an item. It replacesrange(len(items))when you need the position.zip(a, b)walks through two or more collections side by side and stops at the shortest one.reversed(items)goes through a sequence from the end to the start.sorted(items)returns a new sorted list, so you can loop in order without changing the original.
Try It: Positions, Pairs, and Reverse Order
Click Test My Code. Add a fourth name without adding a fourth score and see where zip() stops.
enumerate(), pairs each name with a score using zip(), and counts down from 2 to 0 with reversed(). The end=" " argument keeps the countdown on one line.names = ["Asha", "Ben", "Chen"]
scores = [90, 72, 85]
for index, name in enumerate(names, start=1):
print(index, name)
for name, score in zip(names, scores):
print(f"{name}: {score}")
for i in reversed(range(3)):
print(i, end=" ")
print()names refers to a list of three strings.scores refers to a list of three numbers. The first score belongs to the first name, and so on.enumerate() produces pairs of a number and an item, and the loop unpacks each pair into index and name. With start=1 the numbering begins at 1 instead of 0.1 Asha, 2 Ben, and 3 Chen.zip() pairs the first name with the first score, the second with the second, and so on.Asha: 90, Ben: 72, and Chen: 85.reversed(range(3)) goes through 0, 1, 2 from the end, so i is 2, then 1, then 0.end=" " replaces the normal line break with a space, so the numbers are printed side by side.print() outputs the line break that ends the line. The output of the countdown is 2 1 0.break, continue, and else
Two keywords change the normal flow of a loop. break leaves the loop at once, and the program continues after the loop. continue skips the rest of the current repetition and jumps to the next item. A for loop can also have an else block. It runs when the loop reaches the end of its items without being stopped by break. This is useful for searching: the else block is the “not found” case.
Try It: Skipping and Stopping
Click Test My Code. Then change 20 to 4, so that no even number is above 10, and watch the else block run.
continue. Small even numbers are printed. When a number matches, the loop prints it and stops with break, so the else block is skipped.numbers = [3, 8, 12, 5, 20]
for n in numbers:
if n % 2 != 0:
continue
if n > 10:
print("First even number above 10:", n)
break
print("Even:", n)
else:
print("No even number above 10")numbers refers to a list of five integers.n takes the values 3, 8, 12, 5, and 20 in turn, until the loop is stopped.3 the condition is true.continue ends this repetition at once. The odd numbers 3 and 5 are skipped in this way.8 is even but not above 10, so the condition is false. The number 12 is even and above 10, so it is true.12. The output is First even number above 10: 12.break leaves the loop completely, so the values 5 and 20 are never examined.8, which is even and not above 10. The output is Even: 8.else belongs to the for loop, not to an if. It runs only if the loop finished all its items without a break.break.Nested Loops
A loop can contain another loop. For every repetition of the outer loop, the inner loop runs completely from start to finish. Nested loops are the natural way to work with rows and columns, such as tables, grids, and combinations. A loop that repeats 3 times with an inner loop that repeats 3 times runs the inner block 9 times in total. Each level of nesting adds another level of indentation.
Try It: A Multiplication Grid
Click Test My Code. Change both range(1, 4) to range(1, 6) to make a larger grid.
print() starts a new row.for row in range(1, 4):
for col in range(1, 4):
print(f"{row * col:3}", end="")
print()row takes the values 1, 2, and 3. Everything indented below this line runs once for each row.col takes the values 1, 2, and 3. The inner loop starts again from the beginning for every new row.:3 pads each number to a width of 3 characters so that the columns line up, and end="" keeps the next cell on the same line. The first row is 1 2 3.print() is indented under the outer loop only, so it runs once per row, after the inner loop has finished. It ends the line. The second row is 2 4 6 and the third is 3 6 9.Building Lists with Loops
A for loop is the usual way to build a new list: start with an empty list and use append() inside the loop. A list comprehension is a shorter form of the same idea that you will meet in a later lesson. Loops are also how you count matches, for example how often a letter appears in a word.
Try It: Squares, Evens, and Counting
Click Test My Code. Change the letter that is counted from "l" to "e".
append(). It then builds a list of even numbers with a list comprehension, and finally counts how many times the letter l appears in a word.squares = []
for n in range(1, 6):
squares.append(n ** 2)
print(squares)
evens = [n for n in range(10) if n % 2 == 0]
print(evens)
word = "level"
count = 0
for ch in word:
if ch == "l":
count += 1
print(count)squares starts as an empty list, which the loop will fill.n takes the values 1, 2, 3, 4, and 5.n ** 2 is the square of n, and append() adds it to the end of the list.[1, 4, 9, 16, 25].if. It collects every n from 0 to 9 for which n % 2 == 0 is true.[0, 2, 4, 6, 8].word refers to the string "level".count starts at zero.ch becomes "l", "e", "v", "e", and "l"."l", which happens twice.if inside the for. It runs for the first and the last letter.2.Using for Loops with User Input
Loops let a program process any amount of data. A common way to read several values at once is to ask for one line, split it into words, and loop over the words. Remember that every word is still text, so convert it with int() or float() before calculating.
Try It: A Multiplication Table
The Program Input box is already filled with 7. Click Run Code straight away, then try another number such as 12.
for loop with range(1, 11) to print the multiplication table of that number from 1 to 10.n = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")input() reads the text 7, and int() converts it to the integer 7.range(1, 11) gives the numbers 1 to 10, because the stop value 11 is not included.7 x 1 = 7 to 7 x 10 = 70.Try It: Sum, Average, and Largest
The Program Input box is filled with 4 8 15 16 23 42. Click Run Code, then enter your own numbers separated by spaces.
numbers = input("Enter numbers separated by spaces: ").split()
total = 0
largest = None
for text in numbers:
value = float(text)
total += value
if largest is None or value > largest:
largest = value
print(f"Count: {len(numbers)}")
print(f"Sum: {total}")
print(f"Average: {total / len(numbers):.2f}")
print(f"Largest: {largest}")input() reads the line, and split() turns it into a list of six strings: ["4", "8", "15", "16", "23", "42"].total starts at 0.largest starts as None, which means that no number has been seen yet.text takes each word in turn.float(text) turns the text into a number, so that it can be added and compared.108.0.largest is still None. After that it is true only when the new value is bigger than the current largest value.42.0.Count: 6.Sum: 108.0.Average: 18.00.Largest: 42.0.Tip: Loop over the items directly. Writefor fruit in fruits:instead offor i in range(len(fruits)):followed byfruits[i]. When you need the position as well, useenumerate().
Common Mistakes with for Loops
- Forgetting that the stop value is excluded:
range(5)gives 0 to 4, not 1 to 5. Userange(1, 6)to count from 1 to 5. - Forgetting the colon or the indentation: the
forline must end with:, and the body must be indented, otherwise Python raises aSyntaxErroror anIndentationError. - Looping over a number:
for i in 5:raises aTypeError, because an integer is not iterable. Userange(5). - Changing a list while looping over it: adding or removing items of the list you are looping over gives confusing results. Loop over a copy, such as
for x in items[:]:, or build a new list. - Resetting the accumulator inside the loop: writing
total = 0inside the loop erases the total on every repetition. Create it before the loop. - Using floats in range():
range(0, 1, 0.1)raises aTypeError. Loop over integers and divide, as ini / 10. - Using
range(len(items))without a need: it is longer and easier to get wrong than looping over the items, or usingenumerate(). - Misreading for-else: the
elseblock runs when the loop was not stopped bybreak, not when the loop is empty or when a condition is false.
Key Takeaways
- A
forloop goes through the items of any iterable and runs its indented block once per item. range(stop),range(start, stop), andrange(start, stop, step)produce integers, and the stop value is never included.- Strings give characters, dictionaries give keys by default, and
items()gives key and value pairs. - Create accumulators such as totals, counts, and result lists before the loop and update them inside it.
enumerate(),zip(),reversed(), andsorted()make loops shorter and clearer.breakstops the loop,continueskips to the next item, andelseruns when the loop finishes without abreak.- In nested loops, the inner loop runs completely for every repetition of the outer loop.
Frequently Asked Questions
What is a for loop in Python?
A for loop repeats a block of code once for each item of an iterable such as a list, a string, a dictionary, or a range. It is written as for item in iterable: followed by an indented block. On each repetition the next item is stored in the loop variable.
How does the range() function work in Python?
The range() function produces a sequence of integers. range(5) gives 0 to 4, range(2, 8) gives 2 to 7, and range(0, 20, 5) gives 0, 5, 10, 15. The stop value is never included, and a negative step counts down.
How do I get the index in a for loop in Python?
Use enumerate(), for example for i, item in enumerate(items):. It gives the position and the item together. Add start=1 to begin counting at 1 instead of 0.
How do I loop through a dictionary in Python?
A plain for loop over a dictionary gives its keys. Use .values() to loop over the values, and .items() to loop over key and value pairs, for example for key, value in data.items():.
What is the difference between a for loop and a while loop?
A for loop goes through a known collection or a known number of repetitions. A while loop repeats as long as a condition is true, which makes it better when you do not know in advance how many repetitions are needed.
What does else do in a Python for loop?
The else block of a for loop runs when the loop reaches the end of its items without being stopped by break. If the loop is stopped by break, the else block is skipped. It is often used for the “not found” case of a search.
How do I loop backwards in Python?
Use reversed(), as in for item in reversed(items):, or use a range with a negative step, such as range(10, 0, -1). Reversed does not change the original list.
How do I stop or skip an iteration of a for loop?
Use break to leave the loop completely, and continue to skip the rest of the current repetition and go on with the next item. Both are usually placed inside an if statement.