Python for-in Loop


What is a for-in Loop in Python?

The for-in loop in Python is used to iterate over a sequence (like a list, tuple, string, or dictionary). It loops through each item in the iterable, one by one.

The for-in loop is used in Python to iterate over iterable objects like:

  • Lists
  • Strings
  • Tuples
  • Dictionaries
  • Sets
  • Ranges

It is one of the most commonly used control flow structures in Python.


Syntax of for-in Loop:

for variable in iterable:
    # code block
  • variable: The name of the variable that takes each value
  • iterable: Any object capable of returning its elements one at a time (e.g., list, tuple, range, etc.)


Example 1: Iterate Over a List

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry


Example 2: Iterate Over a String

for char in "Python":
    print(char)

Output:

P
y
t
h
o
n

Explanation:

Each character is treated as an element in the string iterable.



Example 3: Use with range() (Loop Through Numbers)

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

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Explanation:

range(1, 6) gives numbers from 1 to 5.



Example 4: Loop with random Module

import random

for i in range(5):
    print("Random number:", random.randint(1, 100))

Output (Sample):

Random number: 42
Random number: 7
Random number: 89
Random number: 15
Random number: 67

Explanation:

random.randint(a, b) returns a random integer between a and b.



Example 5: Iterate Over a Dictionary

student = {"name": "Alice", "age": 22, "course": "Python"}

for key in student:
    print(key, ":", student[key])

Output:

name : Alice
age : 22
course : Python

Alternative using .items():

for key, value in student.items():
    print(key, "=", value)


Example 6: Using enumerate() for Index Tracking

colors = ["red", "green", "blue"]

for index, color in enumerate(colors):
    print(f"Color at index {index} is {color}")

Output:

Color at index 0 is red
Color at index 1 is green
Color at index 2 is blue

Explanation:

enumerate() lets you loop with index and value.



Use Cases of for-in Loop in Python

Use Case Example
Loop through list for item in my_list:
Loop through string for char in my_string:
Loop with range for i in range(n):
Loop with random numbers random.randint()
Loop with dictionary for key in dict: or for k,v in dict.items()
Loop with index for i, val in enumerate(iterable):


Common Mistakes to Avoid

  • Using for i = 0 like in C/C++ (invalid in Python)
  • Always use for variable in iterable:
  • Forgetting the colon : and indentation