FOR LOOP IN PYTHON

Photo of author

By Jackson Taylor

Home » Electronics Topics » Python & OpenCv » FOR LOOP IN PYTHON

A for loop in Python repeats a block of code once for every item in a sequence. The sequence can be a string, a list, a tuple, a dictionary, a range of numbers, or anything else you can iterate over. If you are just getting started with Python, the for loop is one of the first tools worth learning, because it replaces a lot of repetitive code with a few clear lines.

This guide explains the syntax, walks through the original string example, and then covers lists, range(), break, continue, nested loops and the mistakes beginners make most often.

Basic syntax of a for loop

The structure is always the same: the keyword for, a variable name, the keyword in, the sequence, and a colon. The indented lines below it form the loop body.

for item in sequence:
    # code that runs once per item
    print(item)

On each pass, Python takes the next value from the sequence and assigns it to the loop variable. When the sequence runs out, the loop ends and the program continues with the next unindented line.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video

Example: looping over a string

A string is a sequence of characters, so a for loop can step through it one character at a time. Here is the program from the original article, written in Python 3 syntax.

Program

ab = '1hh'
for xz in ab:
    print(xz)

Output

1
h
h

The variable xz receives '1' first, then 'h', then 'h' again. Each value is printed on its own line.

Note that the original version used print xz without parentheses. That is Python 2 syntax and causes a syntax error in Python 3, where print is a function and needs parentheses.

more examples

Looping over a list

Lists are the most common thing to loop over. The loop variable takes each element in order.

colors = ['red', 'green', 'blue']
for color in colors:
    print(color)

This prints each color on its own line. The same pattern works for tuples, sets and the keys of a dictionary.

See also
SERVICES

Looping over a dictionary

By default, looping over a dictionary gives you its keys. Use .items() to get keys and values together.

ages = {'Anna': 30, 'Ben': 25}
for name, age in ages.items():
    print(name, age)

Using range() to repeat a set number of times

When you want to repeat something a fixed number of times, or work with numbers, use range(). It produces a sequence of integers and accepts up to three arguments: start, stop and step. The stop value is never included.

for i in range(5):
    print(i)

This prints 0, 1, 2, 3 and 4. Counting starts at zero by default.

for i in range(1, 6):
    print(i)

for i in range(0, 10, 2):
    print(i)

The first loop prints 1 to 5. The second prints 0, 2, 4, 6 and 8, because the step is 2.

Getting the index with enumerate()

Sometimes you need both the position and the value. Instead of managing a counter yourself, use enumerate().

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

This prints each fruit with a number starting at 1. If you leave out start=1, the numbering begins at 0.

Controlling a loop with break and continue

Two keywords let you change how a loop runs.

  • break stops the loop immediately, even if items remain.
  • continue skips the rest of the current pass and moves to the next item.
for n in range(1, 10):
    if n == 3:
        continue
    if n == 6:
        break
    print(n)

This prints 1, 2, 4 and 5. The number 3 is skipped, and the loop stops when it reaches 6. Conditions like these rely on an if statement, so it helps to be comfortable with that first.

The else clause on a for loop

A for loop can have an else block. It runs only if the loop finished normally, meaning it was not stopped by break.

for n in [2, 4, 6]:
    if n % 2 != 0:
        print('Found an odd number')
        break
else:
    print('All numbers are even')

Here the list holds only even numbers, so the loop completes and the else message is printed.

See also
What Does a Negative Voltage Mean? Understanding Electrical Potential in Circuits

Nested for loops

You can place one loop inside another. The inner loop runs completely for every pass of the outer loop.

for row in range(1, 4):
    for col in range(1, 4):
        print(row * col, end=' ')
    print()

This prints a small 3 by 3 multiplication table. The end=' ' argument keeps the numbers on the same line, and the empty print() starts a new line after each row.

A quick note on list comprehensions

Once you are comfortable with for loops, you will see a shorter form for building lists.

squares = [n * n for n in range(5)]

This gives [0, 1, 4, 9, 16]. It does the same job as a loop that appends to a list, just in one line. For anything complicated, a regular loop is usually easier to read.

For loop vs while loop

Use a for loop when you know what you are iterating over, such as a list of items or a number of repetitions. Use a while loop when you need to keep going until a condition changes and you do not know in advance how many passes that will take. In most everyday Python code, the for loop is the better first choice.

Common mistakes to avoid

  • Forgetting the colon. The for line must end with :.
  • Wrong indentation. The loop body must be indented consistently, usually four spaces.
  • Off-by-one errors with range(). range(5) stops at 4, not 5.
  • Changing a list while looping over it. Adding or removing items during the loop can skip elements. Loop over a copy, or build a new list instead.
  • Using Python 2 print syntax. Write print(x), not print x.

Where you will use for loops

For loops show up everywhere: reading lines from a file, processing sensor readings, checking each item in a list, or repeating an action on hardware. They are common in hobby electronics too, so if you want practice, try some of these Raspberry Pi Python projects and notice how often a loop does the repetitive work.

See also
PIC16F877A-HITECH C-Digital Output & Input

FAQ

What is a for loop in Python?

A for loop runs a block of code once for each item in a sequence such as a string, list, tuple or range. The loop variable holds the current item on each pass.

How do I loop a specific number of times in Python?

Use for i in range(n):, where n is the number of repetitions. The variable i will count from 0 up to n - 1.

Can I loop over a string in Python?

Yes. A string is a sequence of characters, so for ch in 'hello': gives you one character per pass, as in the example above.

The Ultimate Money-Saving DIY Skill

From power tools and solar banks to your car, batteries are the most expensive part of your gear. Master the step-by-step DIY system to bring dead batteries back to life.

Get the Step-by-Step Guide

Why does print xz give an error?

That is Python 2 syntax. In Python 3, print is a function, so you must write print(xz).

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works