Iterating with a for loop is a common way to go through each element of an iterable in Python. The basic syntax of a for loop in Python is:
for variable in iterable: # code to be executed for each element of the iterable |
The variable represents a temporary variable that will hold each element of the iterable as the loop goes through it. The code block that follows the for statement will be executed for each element of the iterable.
Here's an example of iterating through a list with a for loop:
fruits = ["apple", "banana", "cherry"]for fruit in fruits: print(fruit) |
In this example, we define a list of fruits, and then use a for loop to iterate through the list. For each element in the list, the loop assigns the value to the variable fruit, and then prints it.
You can also iterate through other types of iterables, such as strings, tuples, and dictionaries. For example, here's how you could iterate through a string:
message = "Hello, world!"for character in message: print(character) |
In this example, we use a for loop to iterate through the characters in the string message, and print each character on a separate line.