Control Structures

The "range" Function

range(start, end, step)

Returns an iterator from [start, end), and you can add a step number like:

range(0, 10, 2)

The current range index will add in steps of 2.

"else" in "for" Loops

An else statement after a for, is a block of code that will be executed after the loop ends.

Using "pass" Statement

Use pass to fill empty blocks like if, for, class or etc.

Iterator

Are objects which implements the iterator protocol:

  • __iter__()

  • __next__()

string, List, Tuple, Dictionary and Set are all iterable objects.

You can call iter() function on them and iterate them with next().

for loops automatically create iterators on objects and execute next() at each loop.

Creating iterators

You can create iterators by implementing the __iter__() and __next__() methods.

To avoid an iterator running forever, raise StopIteration.

Last updated