Using Loops to Iterate Over Data in Python

Loops are one of the most powerful tools in programming, enabling you to perform repetitive tasks with ease. In this lesson, we'll explore how to use loops in Python to iterate over various types of data structures.

Why Use Loops?

Loops allow you to automate tasks by repeatedly executing a block of code. They are especially useful when working with collections of data such as lists, tuples, dictionaries, and even strings.

Types of Loops in Python

Iterating Over Lists with For Loops

Let's start with a simple example using a for loop to iterate over a list.

# Example: Iterating through a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

This script outputs each item in the list on a new line:

apple
banana
cherry

Using While Loops for Conditional Iteration

A while loop is ideal when you want to repeat an action until a specific condition is met.

# Example: Counting down with a while loop
count = 5
while count > 0:
    print(count)
    count -= 1

The above code counts down from 5 to 1 and stops once the condition count > 0 is no longer true.

Advanced: Iterating Over Dictionaries

Dictionaries require a slightly different approach since they consist of key-value pairs. Here's how you can loop through them:

# Example: Iterating through a dictionary
prices = {'apple': 1.2, 'banana': 0.8, 'cherry': 2.5}
for item, price in prices.items():
    print(f'{item}: ${price}')

This will output:

apple: $1.2
banana: $0.8
cherry: $2.5

Conclusion

Loops are indispensable in Python programming. Whether you're iterating over simple lists or complex dictionaries, understanding how loops work will help you write efficient, clean, and maintainable code. Practice these examples to master the art of iteration!