1. Iterating Over a List 8.
Using range()
my_list = [1, 2, 3, 4, 5] Basic Usage
for item in my_list: for i in range(5):
print(item) print(i)
2. Iterating Over a Tuple With Start, Stop, and Step
my_tuple = (1, 2, 3, 4, 5) for i in range(1, 10, 2):
for item in my_tuple: print(i)
print(item)
9. Iterating with Index Using enumerate()
3. Iterating Over a String my_list = ['a', 'b', 'c']
my_string = "hello" for index, value in enumerate(my_list):
for char in my_string: print(index, value)
print(char)
10. Iterating Over Multiple Sequences with zip()
4. Iterating Over a Dictionary names = ['Alice', 'Bob', 'Charlie']
my_dict = {'a': 1, 'b': 2, 'c': 3} scores = [85, 92, 78]
for key in my_dict: for name, score in zip(names, scores):
print(key) print(name, score)
5. Keys and Values 11. List Comprehensions (a compact form of for loop)
my_dict = {'a': 1, 'b': 2, 'c': 3} squares = [x**2 for x in range(10)]
for key, value in my_dict.items(): print(squares)
print(key, value)
12. Nested for Loops
6. Values Only for i in range(3):
my_dict = {'a': 1, 'b': 2, 'c': 3} for j in range(3):
for value in my_dict.values(): print(i, j)
print(value)
13. Using for with else
7. Iterating Over a Set for item in [1, 2, 3]:
my_set = {1, 2, 3, 4, 5} print(item)
for item in my_set: else:
print(item) print("Loop completed without break")