Python - For Loops



Python for Loop

The for loop in Python has the ability to iterate over the items of any sequence, such as a list, tuple or a string.

Syntax

for iterating_var in sequence:
   statements(s)

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.

Flowchart

The following flow diagram illustrates the working of for loop −

forloop

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 these methods.

Python's built-in range() function returns an iterator object that streams a sequence of numbers. We can run a for loop with range as well.

for Loop with Strings

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

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='')

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.

for Loop with Tuples

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.

numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
   total+=num
print ("Total =", total)

Output

On executing, this code will produce the following output −

Total = 539

for Loop with Lists

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.

numbers = [34,54,67,21,78,97,45,44,80,19]
total = 0
for num in numbers:
   if num%2 == 0:
      print (num)

Output

On executing, this code will produce the following output −

34
54
78
44
80

for Loop with Range Objects

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 −

range(start, stop, step)

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

numbers = range(5)
'''
start is 0 by default,
step is 1 by default,
range generated from 0 to 4
'''
print (list(numbers))
# step is 1 by default, range generated from 10 to 19
numbers = range(10,20)
print (list(numbers))
# range generated from 1 to 10 increment by step of 2
numbers = range(1, 10, 2)
print (list(numbers))

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.

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=' ')

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

for Loop with Sequence Indexes

To iterate over a sequence, we can obtain the list of indices using the range() function

Indices = range(len(sequence))

We can then form a for loop as follows:

numbers = [34,54,67,21,78]
indices = range(len(numbers))
for index in indices:
   print ("index:",index, "number:",numbers[index])

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

for Loop 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.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
   print (x)

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 −

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
   print (x,":",numbers[x])

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 −

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers.items():
   print (x)

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 −

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x,y in numbers.items():
   print (x,":", y)

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 −

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers.keys():
   print (x, ":", numbers[x])

It will produce the same output

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty
Advertisements