The for loop in Python is a common control flow statement that allows you to traverse a sequence (such as a list, tuple, dictionary, etc.) or other iterable objects to perform a specific operation. In Python, there are many uses for loops, and I'll introduce a few of them and examples below.
1.Traverse the list.
You can use a for loop to iterate through a list and perform a specific action on each element. For example, the following ** will print each element in the list:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item) output:
2.Use the range() function.
If you need to generate a sequence of numbers, you can use the range() function in combination with a for loop. For example, the following ** will print numbers from 1 to 5:
for i in range(1, 6):
print(i) output:
3.Traverse the dictionary.
You can use a for loop to iterate through a dictionary and perform a specific action on each key-value pair. For example, the following ** will print each key-value pair in the dictionary:
my_dict =
for key, value in my_dict.items():
print(key, value)
Output: name alice
age 25
city new york
4.Traverse the collection.
Unlike lists and dictionaries, collections are unordered, so you can't traverse the elements in a collection using a for loop. However, you can use a for loop to iterate through each element in the collection and perform a specific action on each element. For example, the following ** will print each element in the collection:
my_set =
for item in my_set:
print(item)