Skip to main content

Loops: for loops (Part 2)

Following our exploration of Loops: for loops (Part 1), this article delves deeper into the world of for loops, covering nested loops and more advanced patterns for iterating over different data structures.


📚 Prerequisites

A basic understanding of Python's for loop.


🎯 Article Outline: What You'll Master

In this article, you will learn:

  • How to use nested for loops.
  • How to iterate over dictionaries.
  • How to use enumerate() to get both the index and value.
  • How to use zip() to iterate over multiple sequences at once.

🧠 Section 1: Nested for Loops

A nested loop is a loop inside another loop. This is useful for working with multi-dimensional data structures, like a list of lists (a matrix).

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

for row in matrix:
for element in row:
print(element, end=" ")
print()

Output:

1 2 3 
4 5 6
7 8 9

💻 Section 2: Iterating Over Dictionaries

When you iterate over a dictionary, you can access its keys, values, or both.

Iterating over keys:

my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key) # Output: a, b, c

Iterating over values:

for value in my_dict.values():
print(value) # Output: 1, 2, 3

Iterating over key-value pairs:

for key, value in my_dict.items():
print(f"key: {key}, value: {value}")

🛠️ Section 3: enumerate() - Getting the Index and Value

The enumerate() function allows you to get both the index and the value of an item in a sequence as you iterate over it.

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")

🔬 Section 4: zip() - Iterating Over Multiple Sequences

The zip() function allows you to iterate over multiple sequences at the same time.

names = ["Alice", "Bob", "Charlie"]
ages = [30, 25, 35]

for name, age in zip(names, ages):
print(f"{name} is {age} years old.")

💡 Conclusion & Key Takeaways

You've now learned some more advanced for loop patterns that will allow you to write more powerful and efficient code.

Let's summarize the key takeaways:

  • Nested for Loops: A loop inside another loop, useful for multi-dimensional data.
  • Iterating Over Dictionaries: You can iterate over keys, values, or key-value pairs.
  • enumerate(): Get both the index and value of an item.
  • zip(): Iterate over multiple sequences at once.

Challenge Yourself: Write a script that uses a nested for loop to print a multiplication table from 1 to 10.


➡️ Next Steps

In the next article, we'll learn about another type of loop: "Loops: while and do-while loops".

Happy coding!


Glossary (Python Terms)

  • Nested Loop: A loop inside another loop.
  • enumerate(): A built-in function that adds a counter to an iterable.
  • zip(): A built-in function that aggregates elements from two or more iterables.

Further Reading (Python Resources)