The syntax of a for loop in Python is as follows:
Explanation: The for keyword indicates the start of the loop declaration. variable is a variable that takes the value of each element in the iterable during each iteration of the loop.
iterable is a collection of elements over which the loop iterates. It can be a list, tuple, string, dictionary, or any other iterable object in Python.
The colon (:) at the end of the for statement is necessary and indicates the start of the code block that will be executed for each iteration.
The indented lines after the for statement make up the code block that will be executed during each iteration of the loop.
The loop continues until all the elements in the iterable have been processed.
Create your sequence: First, create the sequence over which you want to iterate using the for loop. The sequence can be a list, tuple, string, or any other iterable data type.
Use the enumerate() function: To access both the elements and their corresponding indices, use the enumerate() function. It takes the sequence as an argument and returns pairs of (index, element) for each item in the sequence.
Set up the for loop: Start the for loop and use two variables (commonly named index and item) to capture the index and element of each item in the sequence.
Perform operations: Within the for loop, you can perform any desired operations using the index and item variables. These could be printing the elements, modifying the elements, or using them in calculations.
In Python, you can use the enumerate() function along with a for loop to access both the elements and their corresponding indices in a sequence, such as a list or tuple. Here's how you can do it:
Code:
my_list = ['apple', 'banana', 'orange', 'grape']
for index, item in enumerate(my_list):
print(f"Index: {index}, Item: {item}")
0 Comments