
for
Loop
What is loop?
A loop is a control structure that allows you to execute a block of code repeatedly.
Loops are essential tools in programming, allowing us to automate tasks and control the flow of our code efficiently. With loops, you'll have a versatile set of tools at your disposal for tackling various programming challenges.
There are two primary types of loops in Python: for
Loop and While Loop.
A for
loop is used when you have a collection (like a list, tuple, or string
) and you want to iterate over each element one by one. It typically has a fixed number of iterations based on the length of the sequence.
Let's delve into some practical examples to see how these loops work in action.
for
Loop Syntax:
for element in iterables: # Code to be executed for each item in the sequence
iterables
: An iterable is any object that can return its elements one at a time, includinglists, tuples, strings, dictionaries, and sets
.element
: The termelement
refers to a temporary variable used to represent each item in the iterable during a loop's iteration.
Loop through a list
# Create a list fruits = ["apple", "banana", "cherry"]
# Use a for loop to iterate through the listfor fruit in fruits: print(fruit)
Output:
apple
banana
cherry
Explanation
for fruit in fruits
: This line of code iterates through each item in thefruits
list and assigns each item to the variablefruit
during each iteration. It's a bit like asking the computer to check each fruit int the list one by one.print(fruit)
: Inside the loop, this line prints the value of thefruit
variable, which represents the current item from the fruits list. In the first iteration, it will print "apple," then "banana" in the second iteration, and "cherry" in the third and final iteration.
💡 Note: The variable fruit
after the for
keyword acts as a placeholder for each item in the list during iterations and can be renamed, for instance to value
, without affecting the functionality. Here's how this change looks in code:
# Use value as the placeholderfor value in fruits: print(value)
Output:
apple
banana
cherry
Looping through tuples, sets, and strings is identical to looping through lists.
Example of looping through tuples
The for
loop goes through sample_tuple
, and for each value
, it prints the sum of the value
plus 1.
# Create a tuplesample_tuple = (10, 20, 30)
for value in sample_tuple: print(value + 1)
Output:
11
21
31
Example of looping through strings
Strings are also iterable. The for
loop goes through each character of the string, and prints the character.
# Create a stringtext = 'Hello world'
for character in text: print(character)
Output:
H
e
l
l
o
w
o
r
l
d
Loop through dictionaries
The process of looping through dictionaries differs slightly due to their unique method of element access.
When iterating through a dictionary, you typically traverse its key-value pairs. To access these pairs, you utilize the dictionary's built-in method called items()
. This method allows you to access both the keys and their associated values during each iteration. Each key-value pair is a tuple. We've discussed the items()
method in the Data Structures Dictionaries article.
# Create a dictionarysample_dict = {'a': 1, 'b': 2, 'c': 3}
# Use for loop to access each key-value pair as a tuplefor item in sample_dict.items(): print(item)
Output:
('a', 1)
('b', 2)
('c', 3)
As mentioned, sample_dict.items()
yields key-value pairs as tuples, allowing each iteration to access these pairs directly.
However, beyond just accessing the pairs, we aim to access each individual key and value separately. This requires unpacking the tuples.
# Use for loop to access each key-value pair as a tuplefor item in sample_dict.items(): print(item)
# Unpack tuple and assign to variables key, value key, value = item
# Print values of each tuple print(f'key is {key}, value is {value}')
Output:
('a', 1)
key is a, value is 1
('b', 2)
key is b, value is 2
('c', 3)
key is c, value is 3
Explanation
for item in sample_dict.items()
: This line of code iterates each key-value pair of the dictionary as a tuple.key, value = item
: This line assigns the elements of the tuple to distinct variables;key
receives the tuple's first element, andvalue
receives the second.print(f'key is {key}, value is {value}')
: This prints thekey
andvalue
from each iteration.
We can streamline the code and make it more concise by integrating the tuple unpacking directly into the for
loop syntax. Instead of assigning the tuple to a variable and then unpacking it, we directly unpack the tuple within the for
loop syntax.
for key, value in sample_dict.items(): print(f'key is {key}, value is {value}')
Output:
key is a, value is 1
key is b, value is 2
key is c, value is 3
Python dictionaries offer additional methods like keys()
and values()
for retrieving keys and values separately, as covered in the lesson Data Structures Dictionaries. Let's explore their usage within a for
loop.
# Create a dictionarysample_dict = {'year': 2024, 'month': 'Feb', 'date': '03'}
# Use the method keys() to get dictionary's keysfor k in sample_dict.keys(): print(k)
Output:
year
month
date
The keys()
method returns all the keys of a dictionary as an iterable object. Thus, we can use a for
loop to iterate through each key in that iterable.
# use the method values() to get dictionary's values for v in sample_dict.values(): print(v)
Output:
2024
Feb
03
The method values()
returns all the values of a dictionary as an iterable object. This means we can use a for
loop to iterate through each value in that iterable.
Addional Examples of for
Loop
Loop through a range of numbers
Use range()
function to return an iterable sequence of numbers within a specified range.
# Using range() to get an iterable of numbers in the range from 1 to 5# Loop from 1 to 5for number in range(1, 6): print(number)
Output:
1
2
3
4
5
Use enumerate()
to get both index and value of iterales
enumerate()
is a function used to iterate over an iterable, providing both the index and the value of each item in the iterable.
# Create a listfruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits): print(f"Index {index}: {fruit}")
Output:
Index 0: apple
Index 1: banana
Index 2: cherry