Examples For For Loop In Python

3 min read

Python's for loop in Python is a cornerstone of scripting and data processing. Day to day, it allows you to execute a block of statements repeatedly, once for each element found in an iterable such as a list, tuple, dictionary, or even the range of integers. Understanding this construct empowers learners to automate repetitive tasks, analyze datasets, and implement complex logic with minimal boilerplate code. Below you will find step‑by‑step examples, scientific explanations of how the loop iterates internally, practical tips, and answers to frequent questions—all suited to help you become confident in using a for loop in Python right away.

Introduction

When you first encounter a for loop, it can feel like magic. In reality, it follows a straightforward pattern: assign a temporary variable to each item from the source, run your code, and move to the next item until none remain. Mastering this pattern unlocks the ability to process collections efficiently and to express algorithms in a declarative way. This article walks you through the core mechanics, offers concrete examples, and highlights best practices so you can write clean, readable, and performant code.

How It Works – A Brief Scientific Look

Under the hood, a for loop creates an iterator over the given sequence. Python calls the iterator’s __iter__ method to obtain an iterator object, then repeatedly invokes __next__ to fetch the next element. When the iterator raises StopIteration, the loop terminates gracefully. That's why by understanding this cycle, you can anticipate scenarios where an infinite loop might arise—for instance, if you accidentally reuse the same index or modify the container inside the loop. Recognizing these internal steps helps you debug issues more effectively.

Basic Syntax

for variable in iterable:
    # code block
  • variable: a

- variable: a temporary name that refers to the current item during each iteration. It can be any valid identifier, though choosing a descriptive name (such as user instead of x) makes your code easier to read and maintain.

- iterable: an object capable of returning its members one at a time. Common examples include lists, tuples, strings, dictionaries, sets, and range objects The details matter here..

Simple Examples

Iterating over a list:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

Iterating over a string treats each character as an item:

for letter in "Python":
    print(letter)

When looping through a dictionary, the variable receives each key by default:

scores = {"Alice": 85, "Bob": 90, "Charlie": 78}
for name in scores:
    print(name, scores[name])

To loop over both keys and values simultaneously, use .items():

for name, score in scores.items():
    print(f"{name} scored {score}")

The range() function generates a sequence of numbers, which is especially useful when you need to repeat an action a specific number of times:

for i in range(3):
    print("Iteration", i)

Loop Control Statements

Python provides three statements to alter the flow of a for loop:

  • break exits the loop immediately.
  • continue skips the rest of the current iteration and moves to the next item.
  • else runs a block of code after the loop finishes, but only if the loop was not terminated by break.

Example using break and else:

for number in range(1, 6):
    if number == 4:
        print("Stopping early")
        break
    print(number)
else:
    print("Loop completed normally")

Output:

1
2
3
Stopping early

Because the loop hit break, the else block does not execute.

Nested Loops

A for loop can contain another for loop. This is useful for processing multidimensional structures, such as matrices or combinations of items:

adjectives = ["red", "big
Latest Batch

What's New Today

People Also Read

Dive Deeper

Thank you for reading about Examples For For Loop In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home