The for keyword in Python is a powerful tool for iterating over sequences, such as lists, tuples, strings, and dictionaries. It enables you to execute a block of code repeatedly for each item in the sequence. This eliminates the need for manual index tracking, making your code concise and readable. Let's explore how to use for loops effectively.

Basic Loop Structure

The fundamental structure of a for loop is:

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

Here's how it works:

  • item: This variable represents the current element from the sequence during each iteration.
  • sequence: This can be any iterable object, such as a list, tuple, string, or dictionary.

Looping Through Lists

Let's start with a simple example of iterating through a list of fruits:

Example 1: Looping Through a List of Fruits

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

for fruit in fruits:
  print(fruit)

Output:

apple
banana
cherry

In this example, the for loop iterates over each element in the fruits list. For each fruit, the code inside the loop prints its name.

Looping Through Strings

Strings are also iterable sequences, allowing you to process each character individually:

Example 2: Looping Through Characters in a String

name = "Python"

for letter in name:
  print(letter)

Output:

P
y
t
h
o
n

The loop iterates over each character in the name string, printing each one.

Looping Through Dictionaries

Dictionaries, with their key-value pairs, require a slightly different approach. We can iterate through the keys, values, or both:

Example 3: Iterating Through Dictionary Keys

person = {"name": "Alice", "age": 30, "city": "New York"}

for key in person:
  print(key)

Output:

name
age
city

Example 4: Iterating Through Dictionary Values

person = {"name": "Alice", "age": 30, "city": "New York"}

for value in person.values():
  print(value)

Output:

Alice
30
New York

Example 5: Iterating Through Dictionary Key-Value Pairs

person = {"name": "Alice", "age": 30, "city": "New York"}

for key, value in person.items():
  print(f"Key: {key}, Value: {value}")

Output:

Key: name, Value: Alice
Key: age, Value: 30
Key: city, Value: New York

Range Function for Number Sequences

The range() function is incredibly useful for generating sequences of numbers. It's often used in conjunction with for loops:

Example 6: Iterating Over a Range of Numbers

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

Output:

0
1
2
3
4

This loop iterates from 0 up to (but not including) 5.

You can also specify a starting number and step value:

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

Output:

2
4
6
8

Nested Loops

For complex tasks, you can nest for loops within each other:

Example 7: Nested Loop for Multiplication Table

for i in range(1, 6):
  for j in range(1, 6):
    print(f"{i} x {j} = {i * j}")
  print("----")

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
----
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
----
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
----
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
----
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
----

Break and Continue Statements

  • break: Exits the innermost loop prematurely.
  • continue: Skips the remaining code in the current iteration and moves to the next one.

Example 8: Using 'break' to Exit Early

for i in range(10):
  if i == 5:
    break
  print(i)

Output:

0
1
2
3
4

Example 9: Using 'continue' to Skip Iterations

for i in range(10):
  if i % 2 == 0:
    continue
  print(i)

Output:

1
3
5
7
9

for Loop: A Versatile Tool

The for loop in Python is a versatile tool for automating repetitive tasks and working with sequences. Mastering its usage is crucial for efficient and elegant Python programming.