For Loop in Python
for‘ loop in Python is a type of loop that allows you to iterate over a sequence (such as a list or a string) or other iterable object, and execute a block of code for each element in the sequence. The basic structure of a ‘
for‘ loop is as follows:
for variable in iterable: # code to be executed for each element
For example, the following ‘
for‘ loop iterates over a list of fruits and prints each one:
fruits = ['apple', 'banana', 'mango'] for fruit in fruits: print(fruit)
The output will be:
apple banana mango
In the above example, ‘
fruits‘ is the iterable and ‘
fruit‘ is the variable that takes on the value of each element in the list as the loop iterates. The code block indented under the ‘
for‘ statement (‘
print(fruit)‘) is executed for each element in the list.
for‘ loop can be used to iterate over any iterable object in python like list, tuple, string, etc. It can also be used with the built-in functions like ‘
Accessing the index in ‘for’ loops
In Python, you can access the index of the current iteration in a
for loop using the ‘
enumerate()‘ function. ‘
enumerate()‘ takes an iterable as an argument (such as a list or a string) and returns an iterator that generates pairs (index, element), allowing you to both iterate over the elements of the iterable and access their indices.
Here is an example of using ‘
enumerate()‘ in a
fruits = ['apple', 'banana', 'mango'] for index, fruit in enumerate(fruits): print(index, fruit)
The output will be:
0 apple 1 banana 2 mango
You can also use the built-in ‘
range()‘ function to create a range of numbers and use them as the index.
fruits = ['apple', 'banana', 'mango'] for i in range(len(fruits)): print(i, fruits[i])
This will give you the same output as above.
Another way to access index in ‘
for‘ loops is by using the ‘
zip()‘ function. ‘
zip()‘ takes two or more iterables as arguments, and returns an iterator that generates pairs containing the nth element from each iterable.
fruits = ['apple', 'banana', 'mango'] for i, fruit in zip(range(len(fruits)), fruits): print(i, fruit)
This will also give you the same output.
It depends on the use case and coding style which one you will choose.