O'Reilly logo

Expert Python Programming - Second Edition by Tarek Ziadé, Michał Jaworski

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Advanced syntax

It is hard to objectively tell which element of language syntax is advanced. For the purpose of this chapter on advanced syntax elements, we will consider the elements that do not directly relate to any specific built-in datatypes and which are relatively hard to grasp at the beginning. The most common Python features that may be hard to understand are:

  • Iterators
  • Generators
  • Decorators
  • Context managers

Iterators

An iterator is nothing more than a container object that implements the iterator protocol. It is based on two methods:

  • __next__: This returns the next item of the container
  • __iter__: This returns the iterator itself

Iterators can be created from a sequence using the iter built-in function. Consider the following example:

>>> i = ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required