MyInternships.in

Python Control Flow

Python For Loops

A for loop lets you go through the items of a sequence — like a list, string or dictionary — one by one, running the same block of code for each item.


for-in Syntax

A for loop uses the pattern for item in sequence:, where sequence can be any iterable such as a list, tuple, string or range. On each pass, item takes the value of the next element automatically — no manual counter needed.

Looping over a list
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Iterating Over a String

Since a string is a sequence of characters, a for loop visits each character in turn.

Looping over a string
Python
for letter in "Python":
    print(letter)

Iterating Over a Dictionary

Looping directly over a dictionary gives you its keys. To get both key and value together, call the .items() method, which is the most common pattern when working with dictionaries.

Looping over a dictionary
Python
student = {"name": "Priya", "age": 21, "city": "Pune"}
for key, value in student.items():
    print(key, "->", value)

Getting the Index with enumerate()

When you need both the position and the value while looping, wrap your sequence with enumerate(). It returns pairs of (index, item), starting from 0 by default, which is far cleaner than managing a separate counter.

Using enumerate
Python
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
    print(index, color)

The for-else Clause

Just like while, a for loop can have an else block that runs only when the loop completes without hitting a break. This is useful for search patterns where you want to know a match was never found.

for with else
Python
numbers = [2, 4, 6, 8]
for n in numbers:
    if n % 2 != 0:
        print("Found an odd number")
        break
else:
    print("All numbers are even")
You want to loop overExample
A listfor item in my_list:
A stringfor ch in "hello":
A dict (keys + values)for k, v in d.items():
A range of numbersfor i in range(5):
💡

Use enumerate() instead of range(len(sequence)) — it is more readable and avoids off-by-one indexing mistakes.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships