Python for Loop: A Beginner’s Guide. In Python, for
the loop is used to iterate over a sequence(Which could be a list, a tuple, a dictionary, a set, or a string) with the loop iterating over each element in the sequence. this makes for
the loop particularly useful for performing a task repeatedly on each sequence element.
Table of Contents
Syntax of the Loop in Python
The basic syntax of a for
loop in Python looks like this.
for element in sequence:
# Body of the for loop
# Perform desired operations
Here, ‘element is the variable that takes the item’s value inside the sequence on each iteration, and ‘sequence’ is the collection you want to iterate over.
Basic Example of for Loop in Python
Let’s start with a simple example that prints each item in a list.
gadgets = ['iphone', 'earphone', 'charger']
for gadget in gadgets:
print(gadget)
Iterating Through a Range
If you want to repeat an action a certain number of times with for
loop, you can use the 'range()'
function with a for
loop.
for i in range(10):
print(i)
The above Code will print numbers from 0 to 9. The range(10)
function generates a sequence of numbers from 0 to 9.
Using Enumerate for Index and Value
Sometimes, you may need both the index and the value when looping through a sequence. This can be achieved by using the enumerate()
function.
gadgets = ['iphone', 'earphone', 'charger']
for index,gadget in enumerate(gadgets):
print(index, gadget)
Looping through Dictionaries
While iterating into a dictionary, you can use the '.items()'
method to retrieve both key and value.
gadget_price = {'iphone':'50000', 'laptop': '70000', 'charger': '2000'}
for gadget,price in gadget_price.items():
print(gadget,price)
Nested for Loop in Python
A for
loop can be nested inside another for
loop to iterate over the item in a nested sequence.
for i in range(3):
for j in range(2):
print(i,j)
The for
loop in Python is a powerful tool for iterating over items in a sequence or executing a block of code a certain number of times. Understanding how to use for
loop will greatly enhance your ability to automate repetitive tasks in Python.
Happy Coding & Learning