DEV Community

Cover image for For Loops in Action: Iterating Through Python Like a Pro
Mary Nyandia
Mary Nyandia

Posted on

For Loops in Action: Iterating Through Python Like a Pro

Looping Through Lists
For loops let you process each item in a list one by one. This is essential for handling collections like shopping lists or datasets.

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

Enter fullscreen mode Exit fullscreen mode

Looping Through Ranges
Using range(), you can generate sequences of numbers. This is useful for repeating tasks a specific number of times.

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

Enter fullscreen mode Exit fullscreen mode

Looping with Index
enumerate() provides both the index and the value, making it easy to track positions while processing items.

for index, fruit in enumerate(fruits):
    print(index, fruit)

Enter fullscreen mode Exit fullscreen mode

My take
For loops simplify repetition. They let you process lists, ranges, and indexed data efficiently, reducing redundancy in your code.

Top comments (0)