Reading Time: < 1 minute
In this tutorial, I will teach you how to use the “for” loop in Python.
The “for” loop is a very useful tool that allows us to iterate over a list or iterable and perform an action for each element.
To get started, you’ll need to have a list or iterable that you want to iterate over. For example, let’s say we have the following list of names:
names = ['John', 'Peter', 'Anna', 'Sophia']
To iterate over this list and perform an action for each element, we can use the following code:
for name in names: print(name)
This would print each name in the list on a different line. You can perform any action you want inside the loop, such as modifying the elements of the list or performing calculations.
The “for” loop also allows us to use the “range” function to iterate over a range of numbers. For example, if we want to print numbers from 1 to 10, we can use the following code:
for i in range(1, 11): print(i)
The “for” loop also allows us to use the “enumerate” function to get the index and value of each element at the same time. For example, if we want to print the index and name of each element in the “names” list, we can use the following code:
for i, name in enumerate(names): print(i, name)
I hope this tutorial has helped you understand how to use the “for” loop in Python.
If you have any questions or need further information, feel free to ask.