PYTHON - for Loops
Python - For Loops
Thefor loopin Python provides the ability to loop over the items of any sequence, such as a list, tuple or a string. It performs the same action on each item of the sequence. This loop starts with theforkeyword, followed by a variable that represents the current item in the sequence. Theinkeyword links the variable to the sequence you want to iterate over. Acolon (:)is used at the end of the loop header, and the indented block of code beneath it is executed once for each item in the sequence.
Syntax of Python for Loop
for iterating_var in sequence:
statement(s)Here, theiterating_varis a variable to which the value of each sequence item will be assigned during each iteration.Statementsrepresents the block of code that you want to execute repeatedly.
Before the loop starts, the sequence is evaluated. If it’s a list, the expression list (if any) is evaluated first. Then, the first item (at index 0) in the sequence is assigned toiterating_varvariable.
During each iteration, the block of statements is executed with the current value ofiterating_var. After that, the next item in the sequence is assigned toiterating_var, and the loop continues until the entire sequence is exhausted.
Flowchart of Python for Loop
The following flow diagram illustrates the working offorloop −
Python for Loop with Strings
Astringis a sequence ofUnicodeletters, each having a positional index. Since, it is a sequence, you can iterate over its characters using the for loop.
Example
The following example compares each character and displays if it is not a vowel (‘a’, ‘e’, ‘i’, ‘o’, ‘u’).
zen = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
'''
for char in zen:
if char not in 'aeiou':
print (char, end='')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.Python for Loop with Tuples
Python’s tupleobject is also an indexed sequence, and hence you can traverse its items with afor loop.
Example
In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers.
numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
total += num
print ("Total =", total)On running this code, it will produce the following output −
Total = 539Python for Loop with Lists
Python’s listobject is also an indexed sequence, and hence you can iterate over its items using afor loop.
Example
In the following example, the for loop traverses a list containing integers and prints only those which are divisible by 2.
numbers = [34,54,67,21,78,97,45,44,80,19]
total = 0
for num in numbers:
if num%2 == 0:
print (num)When you execute this code, it will show the following result −
34
54
78
44
80Python for Loop with Range Objects
Python’s built-inrange()function returns an iterator object that streams a sequence of numbers. This object contains integers from start to stop, separated by step parameter. You can run a for loop with range as well.
Syntax
The range() function has the following syntax −
range(start, stop, step)Where,
- 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.
Example
In this example, we will see the use of range with for loop.
for num in range(5):
print (num, end=' ')
print()
for num in range(10, 20):
print (num, end=' ')
print()
for num in range(1, 10, 2):
print (num, end=' ')When you run the above code, it will produce the following output −
0 1 2 3 4
10 11 12 13 14 15 16 17 18 19
1 3 5 7 9Factorial 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.
<pre class="just-code notranslate language-python" data-lang="python">
Factorial of a number n! = 1 * 2 * … . . * n
</pre>
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.
<pre class="demo-code notranslate language-python" data-lang="python3">
fact=1
N = 5
for x in range(1, N+1):
fact=fact*x
print (“factorial of {} is {}“.format(N, fact))
</pre>
Output
On executing, this code will produce the following output −
<pre class="result notranslate">
factorial of 5 is 120
</pre>
In the above program, change the value of N to obtain factorial value of different numbers.
Python for Loop with Sequence Indexes
To iterate over a sequence, we can obtain the list of indices using the range() function
<pre class="just-code notranslate language-python" data-lang="python3">
Indices = range(len(sequence))
</pre>
Example
We can then form a for loop as follows:
<pre class="demo-code notranslate language-python" data-lang="python3">
numbers = [34,54,67,21,78]
indices = range(len(numbers))
for index in indices:
print (“index:“,index, “number:“,numbers[index])
</pre>
On executing, this code will produce the following output −
<pre class="result notranslate">
index: 0 number: 34
index: 1 number: 54
index: 2 number: 67
index: 3 number: 21
index: 4 number: 78
</pre>
Python for Loop with Dictionaries
Unlike a list, tuple or a string,dictionarydata type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with the for loop.
Example
Running a simple for loop over the dictionary object traverses the keys used in it.
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
print (x)On executing, this code will produce the followingoutput−
10
20
30
40Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with theget()method.
Example
The following example illustrates the above mentioned approach.
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
print (x,":",numbers[x])It will produce the followingoutput−
10 : Ten
20 : Twenty
30 : Thirty
40 : FortyThe 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.
Example
The dict_items object is a list of key-value tuples over which a for loop can be run as follows −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers.items():
print (x)It will produce the followingoutput−
(10, 'Ten')
(20, 'Twenty')
(30, 'Thirty')
(40, 'Forty')Using else Statement with For Loop
Python supports to have an else statement associated with a loop statement. However, theelsestatement is executed when the loop has exhausted iterating the list.
Example
The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 to 20.
#For loop to iterate between 10 to 20
for num in range(10, 20):
#For loop to iterate on the factors
for i in range(2,num):
#If statement to determine the first factor
if num%i == 0:
#To calculate the second factor
j=num/i
print ("%d equals %d * %d" % (num,i,j))
#To move to the next number
break
else:
print (num, "is a prime number")
breakWhen the above code is executed, it produces the following result −
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number