Book Image

Getting Started with Python

By : Fabrizio Romano, Benjamin Baka, Dusty Phillips
Book Image

Getting Started with Python

By: Fabrizio Romano, Benjamin Baka, Dusty Phillips

Overview of this book

This Learning Path helps you get comfortable with the world of Python. It starts with a thorough and practical introduction to Python. You’ll quickly start writing programs, building websites, and working with data by harnessing Python's renowned data science libraries. With the power of linked lists, binary searches, and sorting algorithms, you'll easily create complex data structures, such as graphs, stacks, and queues. After understanding cooperative inheritance, you'll expertly raise, handle, and manipulate exceptions. You will effortlessly integrate the object-oriented and not-so-object-oriented aspects of Python, and create maintainable applications using higher level design patterns. Once you’ve covered core topics, you’ll understand the joy of unit testing and just how easy it is to create unit tests. By the end of this Learning Path, you will have built components that are easy to understand, debug, and can be used across different applications. This Learning Path includes content from the following Packt products: • Learn Python Programming - Second Edition by Fabrizio Romano • Python Data Structures and Algorithms by Benjamin Baka • Python 3 Object-Oriented Programming by Dusty Phillips
Table of Contents (31 chapters)
Title Page
Copyright and Credits
About Packt
Stacks and Queues
Hashing and Symbol Tables


In typical design pattern parlance, an iterator is an object with a next() method and a done() method; the latter returns True if there are no items left in the sequence. In a programming language without built-in support for iterators, the iterator would be looped over like this:

while not iterator.done(): 
    item = 
    # do something with the item 

In Python, iteration is a special feature, so the method gets a special name, __next__. This method can be accessed using the next(iterator) built-in. Rather than a done method, Python's iterator protocol raises StopIteration to notify the loop that it has completed. Finally, we have the much more readable foriteminiterator syntax to actually access items in an iterator instead of messing around with a while loop. Let's look at these in more detail.

The iterator protocol

The Iterator abstract base class, in the module, defines the iterator protocol in Python. As mentioned, it must have a __next__ method...