Python For Loops

For loops in Python are used to iterate over a sequence (like lists, tuples, strings) or other iterable objects.

Basic Syntax


for item in sequence:
  # Code to be executed for each item
  # ...
    

The sequence can be any iterable object. The loop iterates through each item in the sequence, assigning the current item to the variable item in each iteration.

Example 1: Iterating through a List


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

Output:


apple
banana
cherry
    

Example 2: Iterating through a String


message = "Hello, AIT!"
for char in message:
  print(char)
    

Output:


H
e
l
l
o
,
A
I
T
!
    

Example 3: Iterating through a Tuple


coordinates = (10, 20)
for coord in coordinates:
  print(coord)
    

Output:


10
20
    

Example 4: Using the `range()` function


for i in range(5):  # range(5) generates numbers from 0 to 4
  print(i)
    

Output:


0
1
2
3
4
    

Example 5: Iterating with Index


colors = ["red", "green", "blue"]
for i in range(len(colors)):
  print(f"Color at index {i}: {colors[i]}")
    

Output:


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

Example 6: Iterating with `enumerate()` for index and value


numbers = [10, 20, 30]
for index, number in enumerate(numbers):
    print(f"Index: {index}, Number: {number}")
    

Output:


Index: 0, Number: 10
Index: 1, Number: 20
Index: 2, Number: 30
    

Example 7: Looping through Dictionaries


student = {"name": "Muntajeeb", "age": 20, "grade": "A"}
for key, value in student.items():
  print(f"{key}: {value}")
    

Output:


name: Muntajeeb
age: 20
grade: A
    

Important Note

For loops are very versatile and can be used to iterate over various types of sequences or iterables in Python. Always ensure you're working with something that's iterable. Using `range()` is essential when you need to iterate a specific number of times, or if you need the index of the item in the iteration.