DEV Community

Cover image for Iteration Everywhere: Navigating Lists, Dictionaries, and Strings
Mary Nyandia
Mary Nyandia

Posted on

Iteration Everywhere: Navigating Lists, Dictionaries, and Strings

Iterating Over Lists
Iteration lets you process each item in a list, making it easy to handle collections of data.

values = [10, 20, 30]
for value in values:
    print("Value:", value)

Enter fullscreen mode Exit fullscreen mode

Iterating With Index
Using enumerate(), you can access both the index and the value, which is useful for tracking positions.

for index, value in enumerate(values):
    print(index, value)

Enter fullscreen mode Exit fullscreen mode

Iterating Over Dictionaries
Dictionaries can be iterated to access both keys and values, making them ideal for structured data.

info = {"a": 1, "b": 2}
for key, value in info.items():
    print(key, value)

Enter fullscreen mode Exit fullscreen mode

Iterating Over Strings
Strings are sequences too, so you can loop through each character for tasks like text analysis.

for char in "hello":
    print("Character:", char)

Enter fullscreen mode Exit fullscreen mode

My take
Iteration is fundamental for processing collections. Whether lists, dictionaries, or strings, loops let you handle data systematically and efficiently.

Top comments (0)