Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!The for loop in Python has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
If a sequence contains an expression list, it is evaluated first. Then, the first item (at 0th index) in the sequence is assigned to the iterating variable iterating_var.
Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
The following flow diagram illustrates the working of for loop −
Since the loop is executed for each member element in a sequence, there is no need for explicit verification of Boolean expression controlling the loop (as in while loop).
The sequence objects such as list, tuple or string are called iterables, as the for loop iterates through the collection. Any iterator object can be iterated by the for loop.
The view objects returned by items(), keys() and values() methods of dictionary are also iterables, hence we can run a for loop with them.
Python’s built-in range() function returns an iterator object that streams a sequence of numbers. We can run a for loop with range.
Using "for" with a String
A string is a sequence of Unicode letters, each having a positional index. The following example compares each character and displays if it is not a vowel (‘a’, ‘e’, ‘I’, ‘o’ or ‘u’)
Example
Output
On executing, this code will produce the following output −
Btfl s bttr thn gly. Explct s bttr thn mplct. Smpl s bttr thn cmplx. Cmplx s bttr thn cmplctd.
Using "for" with a Tuple
Python’s tuple object is also an indexed sequence, and hence we can traverse its items with a for loop.
Example
In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers.
Output
On executing, this code will produce the following output −
Total = 539
Using "for" with a List
Python’s list object is also an indexed sequence, and hence we can traverse its items with a for loop.
Example
In the following example, the for loop traverses a list containing integers and prints only those which are divisible by 2.
Output
On executing, this code will produce the following output −
34 54 78 44 80
Using "for" with a Range Object
Python’s buil-in range() function returns a range object. Python’s range object is an iterator which generates an integer with each iteration. The object contains integrrs from start to stop, separated by step parameter.
Syntax
The range() function has the following syntax −
Parameters
-
Start − Starting value of the range. Optional. Default is 0
-
Stop − The range goes upto stop-1
-
Step − Integers in the range increment by the step value. Option, default is 1.
Return Value
The range() function returns a range object. It can be parsed to a list sequence.
Example
Output
On executing, this code will produce the following output −
[0, 1, 2, 3, 4] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [1, 3, 5, 7, 9]
Example
Once we obtain the range, we can use the for loop with it.
Output
On executing, this code will produce the following output −
0 1 2 3 4 10 11 12 13 14 15 16 17 18 19 1 3 5 7 9
Example: Factorial of a Number
Factorial is a product of all numbers from 1 to that number say n. It can also be defined as product of 1, 2, up to n.
We use the range() function to get the sequence of numbers from 1 to n-1 and perform cumumulative multplication to get the factorial value.
Output
On executing, this code will produce the following output −
factorial of 5 is 120
In the above program, change the value of N to obtain factorial value of different numbers.
Using "for" Loop with Sequence Index
To iterate over a sequence, we can obtain the list of indices using the range() function
We can then form a for loop as follows:
On executing, this code will produce the following output −
index: 0 number: 34 index: 1 number: 54 index: 2 number: 67 index: 3 number: 21 index: 4 number: 78
Using "for" with Dictionaries
Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with different techniques.
Running a simple for loop over the dictionary object traverses the keys used in it.
On executing, this code will produce the following output −
10 20 30 40
Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with the get() method. Take a look at the following example −
It will produce the following output −
10 : Ten 20 : Twenty 30 : Thirty 40 : Forty
The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them.
The dict_items object is a list of key-value tuples over which a for loop can be run as follows −
It will produce the following output −
(10, 'Ten') (20, 'Twenty') (30, 'Thirty') (40, 'Forty')
Here, "x" is the tuple element from the dict_items iterator. We can further unpack this tuple in two different variables. Check the following code −
It will produce the following output −
10 : Ten 20 : Twenty 30 : Thirty 40 : Forty
Similarly, the collection of keys in dict_keys object can be iterated over. Take a look at the following example −
It will produce the same output −
10 : Ten 20 : Twenty 30 : Thirty 40 : Forty
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.