A Python for loop is a set of instructions that is repeated, or iterated, for every value in a sequence.
Sometimes for-loops are referred to as definite loops because they have a predefined beginning and end as bounded by the sequence.
Table of Contents
Python For loop Syntax
The general syntax of a for-loop block is as follows.
for looping variable in sequence:
……code block
Get Your Free Linux training!
Join our free Linux training and discover the power of open-source technology. Enhance your skills and boost your career! Learn Linux for Free!- A for-loop assigns the looping variable to the first element of the sequence. It executes everything in the code block.
- Then it assigns the looping variable to the next element of the sequence and executes the code block again.
- It continues until there are no more elements in the sequence to assign.
What are the benefits of using a for loop in Python?
A for loop is a programming construct that allows you to repeat a certain set of code multiple times. In Python, the for loop is written as follows:
for item in sequence:
body of the for loop
The body of the for loop will execute once for each item in the sequence. Some benefits of using a for loop in Python include:
- Easier to read and understand than while loops
- Often more efficient than while loops
- Can be used to iterate over arrays, lists, tuples, and strings
Common uses cases for a for loop in Python
Some common uses cases for a for loop in Python include:
- Processing data in a list or array
- Performing operations on all the items in a list or tuple
- Iterating over the characters in a string
- Counting how many times a certain item appears in a list or tuple
Python For Loops Over a List
We can use it with any sequence type (list, string, tuple) plus dictionaries. The most prototypical use of for … in loop is over a list.
Below, it is used to print all the items in the list:
>>> list=[‘Accelerate’, ‘your’, ‘transformation’, ‘with’, ‘Google’, ‘Cloud’]
>>> for i in list:
>>>… print(i)
…
Accelerate
your
transformation
with
Google
Cloud
Python For Loops Over a String
When used on a string, the looping has to go through everything. Well, a string is a sequence of characters, so the iteration is done on every character:
>>> for x in ‘google’:
>>>……print(x)
g
o
o
g
l
e
>>>
Python For Loops Over a Dictionary
we can also use for loop over a dictionary. When for loop in is used on a dictionary, looping is done over its keys, and not over the values or the key:value pairs:
>>> Clouds = {‘Goole’:100, ‘Amazon’:20, ‘IBM’:10, ‘Cisco’:8}
>>> for s in Clouds: # s iterates over keys in clouds
>>>…….print(s)
Amazon
Cisco
Goole
IBM
Of course, the values are retrievable via the keys. Hence, printing both the key and the value looks like:
>>> for s in Clouds: # s iterates over keys in clouds
>>> ……print(s, Clouds[s]) # key, value
Goole 100
Amazon 20
IBM 10
Cisco 8
An alternative is to explicitly instruct the for loop to iterate over the key:value pairs.
The .items() method on a dictionary induces a pseudo-list of (key, value) tuples.
The for loop then can iterate over this list, and the bound variable should also be the tuple type:
>>> Clouds.items() # returns a quasi-list of (key, value) pairs
dict_items([(‘Goole’, 100), (‘Amazon’, 20), (‘IBM’, 10), (‘Cisco’, 8)])
>>> for (k,v) in Clouds.items(): # iterate over (key, value) list
>>> ……print(k, v) # key, value
Goole 100
Amazon 20
IBM 10
Cisco 8
Note that the iteration is in no particular order, although it stays consistent. That’s because dictionaries are inherently orderless.
If we want to go through the dictionary in a particular order (say, alphabetical or numerical), we will have to sort.
Python For loop With range() Function
range() is a function that’s often used with a for loop. range(x,y) creates a list-like object starting with integer x and ending BEFORE y.
The starting point x can be omitted, in which case the list starts with 0. In a looping environment range() works as expected.
In a non-iterative environment, however, we will need to plug in the range() function’s return value into list() to view it as a list:
>>> for i in range(4): # range() in iterative environment
>>> ……print(i)
0
1
2
3
>>> range(4) # non-iterative context: content not visible
range(4)
>>> list(range(4)) # force into list type to see what’s inside
[0, 1, 2, 3]
>>> list(range(2,8))
[2, 3, 4, 5, 6, 7]
example of for loop with length
First, range() together with len(‘Google’) produces a list of indexes for the word:
>>> len(‘Google’)
6
>>> list(range(len(‘Google’)))
[0, 1, 2, 3, 4, 5]
Now, we can iterate through this list of indexes, and it is easy enough to get to the character once you have its index:
>>> for i in range(len(‘Google’)):
>>> ……print(i, ‘Google'[i])
0 G
1 o
2 o
3 g
4 l
5 e
Understanding a nested for loop in Python
A nested for loop is a for loop that is contained within another for loop. In Python, the syntax for nesting a for loop looks like this:
for outer_variable in sequence:
for inner_variable in sequence:
body of the for loops
The body of the inner for loop will execute once for each item in the sequence. The sequence can be any type of iterable object, such as a list, tuple, or string. The body of the outer for loop will execute once for each item in the sequence. The sequence can be any type of iterable object, such as a list, tuple, or string. Some benefits of using nested for loops include:
- – Can be used to process data in a more efficient manner
- – Can be used to iterate through arrays, lists, tuples, and strings more efficiently
- – Often easier to read and understand than while loops.
Difference between for loop and while loop
The primary difference between a for loop and a while loop is that the for loop executes the code block once for each item in the sequence. While loops are often more versatile, they can be a bit harder to read and understand than for loops. Additionally, while loops are not as efficient as for loops when it comes to processing arrays or lists of data.