You are here

Iteration in Python

Iteration- for and while loop:

Iterations are used for repetitive execution of the same block of code over and over. Loop or iteration are popular block of code in all the programming language like basic, PASCAL, C, JAVA, PHP and all others. They can be numeric or collection based.

Type of Iteration

There are two types of iteration:

a) Definite iteration, in which the number of repetitions is specified explicitly in advance. This is implemented using the for loop.

b) Indefinite iteration, in which the code block executes until some condition is met. This type of iteration is implemented using the while loop

How to check if an object is iterable?

we can check whether an object is itrable r not by passing it to the built-in function iter(object). The built-in iter() function will return the type of the iterable.

>>> x=[3,4,5,8,9]

>>> iter(x)

<list_iterator object at 0x7fed9b5ffa30>

How to get the next value of iterable

built-in next() function returns the next value of an iterable.

>>> i=iter(x)

>>> next(i)

3

>>> next(i)

4

>>> next(i)

5

What is an iterable and non iterables

The following table lists some of the iterable and non-iterable objects in python.

Iterable objects

Non iterable objects

string

>>> x=”ram”

>>>iter(x)

Integer

>>>iter(10) or x=10 # then

>>>iter(x) #TypeError:
'integer'
object is not iterable

List

x=[5,7,2,4,9]

>>>iter(x)

Float

>>>iter(3.14) #TypeError:
'float'
object is not iterable

Tuple

>>> x=((3,4),(2,3),(4,5))

>>> iter(x)

Built-in functions

iter(len) # here len is inbuilt pythn function, #TypeError:
'built-in
function
'
object is not iterable

Set and frozenset

>>> x={3,4,5,6,2,3,3,6,7}

>>> iter(x)

Dictionary

>>> x={‘a’:1,’b’:2,’c’:3,’d’:4}

>>> iter(x)

In addition to above said iterable, there are many other objects that are built into Python or defined in modules are designed to be iterable. Example : open files object is iterable and is used to reads data from the file. We in fact can make almost every in-built or user defind object in python be iterable.

How to grab all values of list, set, tuple etc.

To grab all the values of a list, set, tuple etc we can use the built-in functions

list()

set()

tuple()

Examples:

>>> x=[2,5,6,7,3]

>>> list(x)

[2, 5, 6, 7, 3]

>>> x

[3, 4, 5, 8, 9]

>>> list(x)

[3, 4, 5, 8, 9]

>>> set(x)

{3, 4, 5, 8, 9}

>>> set(x)

{3, 4, 5, 8, 9}

>>> tuple(x)

(3, 4, 5, 8, 9)

Definite Iteration or FOR LOOP

Definite iteration, in which the number of repetitions is specified explicitly in advance. This is implemented using the for loop. For loop is used to iterate over a sequence list, tuple, dictionary, string or other iterable objects. It iterates over certain range of numbers. format

for ,var> in <squence> :

…    <body of the loop>

…else:

…    <else block statement>

here the <squence> is a collection of iterable objects—for example, a list or tuple. The statements in the <body of the loop>
are denoted by 4-space indentation, and are executed once for each item in the <sequence>. Here var is a variable that takes the next value of the item inside the sequence each time through the loop untill all the items in the sequence is exhausted.

else code block get executed only when all the values in the sequence get exhausted.

Example:

for i in [0,2,3,4,5,6,9,7]

… print(i)

Generating the sequnce of numbers- range() function

Using list(), set(), tuple() for processing of elements is not efficient for large lists, set or tuple. In python the range of an object can be generate using the range () function. The general format of the range() function is:

range(start_value, stop_value, step-size) where step_size by default is one (1) and can be made as any +ve or -ve step value.

>>> x=10

>>> print(range(x))

range(0, 10)

>>> print(len(range(x)))

10

>>> x=10

>>> for i in range(x,0,-2):

…         print(i)

10

8

6

4

2

For loop with else statement

>>> x=[2,4,6,8,9,7,5]

>>> for i in range(len(x)):

… print(x[i])

… else:

… print(“all values have been printed”)

2

4

6

8

9

7

5

all values have been printed        #this is because of the else statement

Indefinite iteration in python

Indefinite iteration, in which the code block executes until some condition is met. This type of iteration is implemented using the while loop

The while loop in Python is used to iterate over a block of code when we don’t know the number of times to iterate but to iterate only as long as the test expression (condition) is true.

Format of the while() loop

while <test_expression>:
...    <body of while loop >
...else:
...    <else part os statements>

example:

WAP in python to add first 10 natural numbers

>>> x=10
>>> i=1
>>> s=0
>>> while i<=x:
…     s=s+i
…     i=i+1
…     print(s)
… else:
…     print(“Sum of 1st 10 natural numbers is: “,s)

1
3
6
10
15
21
28
36
45
55
Sum of 1st 10 natural numbers is: 55

Break statement:

A break statement is used to exit the loop statement. The else  block will be executed if break has not been executed because of not meeting the condition for break. If the condition becomes true for break, then the else part will not be executed

Example of break statement

>> colors=[‘black’, ‘white’,’red’,’yellow’,’green’]
>>> for i in colors:
…     if i==’red’:
…        break         #breaks the loop if condition was true
…        print(i)
… else:
…     print(‘list ended’)          #if i==’red’ is true then this statement will not be executed

black
white

Continue statement

the continue statement is used to iterate through the next iterable when the condition in the if statement becomes true. It will take control to the top of the loop for next iteration.

Example: Print all natural numbers from 1 to 7 except 5

>>> x=7
>>> for i in range(x):
… if i==5:
… continue
… print(i)
… else:
… print(‘All values except 5 printed’)

0
1
2
3
4
6
All values except 5 printed

Leave a Reply

Top
error: Content is protected !!