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)
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)
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)
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)
My take
Iteration is fundamental for processing collections. Whether lists, dictionaries, or strings, loops let you handle data systematically and efficiently.
Top comments (0)