Monday 10 December 2012

Iterator, Generator and List Compression





Iterator

An iterator is an object representing a stream of data and this object returns the data one element at a time. A Python iterator needs to support a method called __next()__ .This next () method takes no arguments and always returns the next element of the stream. If there are no more elements in the stream,  __next()__ must raise StopIteration exception. 

Here is the example:
 
 
num= []
i = 0
for item in range(10):
        i = i + 4
        num.append(i)
print num

a = iter(num)
print a.next()
print a.next()  

Output

[4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
4
8
>>> a.next()
12
>>> a.next()
16
>>> a.next()
20

Generators
 
Generator is a function which controls the iterations, stop at a point, save the context and resume from where it stopped last. A generator can generate a sequence of numbers and yields the result one at a time. Since generators return one value at a time they take up less memory and behave similar to an iterator. Generators are usually evoked in a loop.

Here is the simple example:-

def fibonacci():
        a = 0
        b = 1
        yield a 
        yield b
        while 1:
                c = a + b
                a, b = b, c
                yield c
d = fibonacci()




List Compression

List comprehension is a concise way of creating lists. We  use list compression when we need to define operations that are to be applied to each element in the list. It simplifies the code, where we have to use multiple statements to get desired output to a more shorter form.

for a in range(10):

          square.append(a*a)

 Here, this can be also done with single line code as given below:

 square = [a*a for a in range(10)]





[Expecting Your Valuable Comments]
Thank You

No comments:

Post a Comment