Mastering For Loops in Python: A Comprehensive Guide
Table of Content:
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Python for loop Syntax
Python for loop can iterate over a sequence of items. The structure of a for loop in Python is different than that in C++ or Java. That is, for(int i=0; i < n; i++) won’t work here. In Python, we use the ‘in’ keyword.
The syntax for a For Loop in Python is as follows:
for variable in sequence: # loop code here
Here, "sequence" could be any iterable object, such as a list, tuple, or string. The "variable" takes on the value of each element in the sequence one by one, with each iteration of the loop.
You can change the name of variable like below:
for x in sequence: # loop body
Python for loop flowchart
Here is a flowchart for Python For Loops:
Looping through a list
Let's look at some examples to get a better understanding of For Loops in Python.
fruits = ["Cabbage", "Spinach", "Cauliflower"] for x in fruits: print(x)
Output:
Cabbage Spinach Cauliflower
Looping Through a String
Strings are iterable objects, they contain a sequence of characters: The for
statement is used to iterate over a sequence of elements, such as a string. The syntax for the for
loop is for variable in sequence:
. In this case, the sequence is "Hello", and the loop variable is x
.
Loop through the letters in the word "Hello":
Code
for x in "Hello": print(x)
Python For Loop that iterates over a string "Hello". The loop variable x
takes on the value of each character in the string "Hello" one by one, with each iteration of the loop.
The output of the code will be:
H e l l o
Looping through a range of numbers
for i in range(5): print(i)
0 1 2 3 4
Using the range() Function: In the second example, we used the range()
function to loop through a range of numbers. The range()
function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number. We can specify the start and step values as well.
for i in range(2, 10, 2): print(i) # Output: # 2 # 4 # 6 # 8
Python for loop that iterates over a dictionary
Here's an example of a Python for loop that iterates over a dictionary:
my_dict = {'name': 'John', 'age': 30, 'country': 'USA'} for key in my_dict: print(key, ':', my_dict[key])
Explanation:
- The
my_dict
dictionary is created, which has three key-value pairs. - The
for
loop starts by iterating over the keys inmy_dict
. - In each iteration, the loop variable
key
takes on the value of each key in the dictionary. - The
print
function is used to print each key-value pair by accessing the values in the dictionary using square bracket notationmy_dict[key]
.
The output of the code will be:
name : John age : 30 country : USA
Note: Another way to iterate over a dictionary is to use the items
method, which returns a view of the dictionary's key-value pairs as a sequence of (key, value)
tuples. Here's an example:
my_dict = {'name': 'Rumman', 'age': 22, 'country': 'India'} for key, value in my_dict.items(): print(key, ':', value)
The output of the code will be:
name : Rumman age : 22 country : India