Using iterables

Iterables are similar to generators except for a key difference, we can go on and on with an iterable, that is, once we have exhausted all the elements in a sequence, we can again start accessing it from the beginning unlike a generator.

They are object-based generators that do not hold any state. Any class with the iter method that yields data can be used as a stateless object generator.

Getting ready

Let's try to understand iterables with a simple example. This recipe should be easy to follow if you have understood the previous recipes on generators and iterators.

How to do it…

Let's create a simple iterable called SimpleIterable and show some scripts that manipulate it:

# 1.	Let us define a simple class with __iter__ method.
class SimpleIterable(object):
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __iter__(self):
        for x in range(self.start,self.end):
            yield x**2

#  Now let us invoke this class and iterate over its values two times.
c = SimpleIterable(1,10)

# First iteration
tot = 0
for val in iter(c):
    tot+=val

print tot

# Second iteration
tot =0
for val in iter(c):
    tot+=val

print tot

How it works..

In step 1, we created a simple class that is our iterable. The init constructor takes two arguments, start and end, similar to our earlier example. We defined a function called iter, which will give us our required sequence. In this given range of numbers, the square of these numbers will be returned.

Next, we have two loops. We iterated through our range of numbers, 1 to 10, in the first loop. When we will run the second for loop, you will notice that it once again iterates through the sequence and doesn't raise any exceptions.

See also

  • Using Iterators recipe in Chapter 1, Using Python for Data Science
  • Generating an Iterator - Generators recipe in Chapter 1, Using Python for Data Science
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset