Iteration in Python


Iteration 

The repetition of a process is called iteration. Iteration is defined as the act of process of repeating.

Iteration can include repetition of a sequence of operations in order to get ever closer to a desired result.

Iteration can also refer to a process to perform a process over and over again repeatedly for a specific number of times or until a specific condition has been met. 

There are two types of iterations-

1. Count controlled loops

Used for iterating steps a specific number of times. It is used when the number of iterations to take place is already known. It is uses a converter to keep track of how many times the set of commands has been repeated.

This loops are executing using for statements.

2. Condition-Controlled Loops

Used for iterating steps continuesly until a condition is met. It is used when the number of iterations to take place is unknown.

The algorithm tests the condition to sere if it is true. If true the algorithm executes a command. If false, the algorithm goes back to step 1 and will continue to go back until the condition becomes true.

This loops are executed using while statements.

Iterator VS Iterable

Lists, tuples, dictionary and sets are all iterable objects. They are iterable containers which you can get an iterator from.

All these objects have a  iter() method which is used to get an iterator.

Example

# return an iterator from a tuple and print each value

mytuple=("apple","banana","grapes")

myit=iter(mytuple)

print(next(myit))

print(next(myit))

print(next(myit))

Output

apple

banana

grapes

Looping through an Iterator 

We can also use a for loop to iterate through an iterable object.

Example

# Iterate the values of a tuple

mytuple=("apple","banana","grapes")

for i in mytuple:

        print(i)

# Iterate the characters of a string.

mystr="banana"

for x in mystr:

        print(x)


Output

apple

banana

grapes

b
a
n
a
n
a




No comments:

Post a Comment