Let's Iterate

@kshitij10496

Open Source Developer

What is iteration?

Repeated execution of a set of statements

Text

How do we iterate in Python?

for loop

while loop

for item in items:
    # perform repeated operations
    # on each "item"
while some_condition:
    # perform operations on some data
  • Loop over a list printing each item
  • Convert a number to binary

for

while

Terminology

Iterable

 

Iterator

Iterable

__iter__ method

 

__iter__ method must return an "iterator" object

Iterator

Python3 : __next__() method

Python2: next() method

 

StopIteration Exception

Trick: Define a class with both __iter__() and __next__()

The "iterator" protocol

Examples

Iterables

list, tuple, dict, string, files

 

Basically, anything that can be used with a for loop

for item in my_iterable:
    # perform operations on item
    print(item)
for item in iter(my_iterable):
    # perform operations on item
    print(item)

Examples

Iterators

In []: squares = [1, 4, 9, 16, 25]

In []: squares_iter = iter(squares)

In []: first_square = next(squares_iter)

....

In []: last_square = next(squares_iter) # 25

In []: new_square = next(squares_iter) # What happens now ?

Call __iter__() method on iterable object

Use next() on the iterator to generate the next item

How to write one?

class yrange(object):

    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i < self.n:
            i = self.i
            self.i += 1
            return i
        else:
            raise StopIteration

The Awesome

class TodoList(object):
    
    def __init__(self, todos=None):
        self.todos = todos
        
    def __iter__(self):
        return iter(self.todos)

No __next__ method?

Our for loop

iter_items = iter(items)

while True:
    try:
        item = next(iter_items)
    except StopIteration:
        break
    else:
        return item

Under the Hood

Types of Iterables

  • Sequences : list, tuple, str

  • Mappings : dict, OrderedDict

  • Generators

Can iterables be infinite?

Yes !

How to iterate over infinite iterables?

Creating iterators over it?

DON'T !

I REPEAT - DON'T!

natural_numbers = [i for i in itertools.count()]

Try this at your own risk!

Generators FTW!

Let's be Laaazzzzyyyyyy!

 

Powerful way to implement iterators

How do I create one?

Generator Functions

Tuple Comprehensions

Generator Functions

def natural_numbers(start=1):
        n = start
        while True:
            yield n
            n += 1

all_natural_numbers = natural_numbers()

But you have no return statement :(

yield ! yield ! yield!

Coroutines vs Subroutines

Tuple Comprehensions

natural_numbers = (i for i in itertools.count())

Just Kiddin' !

Generator expressions

Takeaways

  • Iterables and iterators
  • Create more iterables
  • Use generators
  • Generator expressions;
    not tuple comprehensions

Happy Coding!

deck

By Kshitij Saraogi

deck

  • 543