Iterating in Python means going through each element of an iterable, such as a list, tuple, string, or dictionary, one by one.
To iterate over an iterable, you can use a loop, such as a for loop. Here's an example of iterating over a list:
fruits = ["apple", "banana", "orange"]for fruit in fruits: print(fruit) |
for loop iterates over the fruits list and assigns each element to the fruit variable one by one. The print statement inside the loop then prints each element of the list on a separate line.You can also use the enumerate function to iterate over an iterable and keep track of the index of each element. Here's an example:
fruits = ["apple", "banana", "orange"]for i, fruit in enumerate(fruits): print(i, fruit) |
In this example, the enumerate function is used to iterate over the fruits list and return a tuple for each element, containing its index and value. The for loop then unpacks each tuple into the i (index) and fruit variables and prints them on separate lines.
Iterating over a dictionary requires a slightly different approach, as you need to iterate over its keys, values, or items. Here's an example of iterating over the keys of a dictionary:
person = {"name": "Alice", "age": 30, "city": "New York"}for key in person: print(key, person[key]) |
In this example, the for loop iterates over the keys of the person dictionary and prints each key-value pair on a separate line.