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
Contributors
Preface
8
Stacks and Queues
10
Hashing and Symbol Tables
Index

Improving list traversal


If you notice how we traverse our list. That one place where we are still exposed to the node class. We need to use node.data to get the contents of the node and node.next to get the next node. But we mentioned earlier that client code should never need to interact with Node objects. We can achieve this by creating a method that returns a generator. It looks as follows:

    def iter(self):
        current = self.tail
        while current:
            val = current.data
            current = current.next
            yield val  

Now list traversal is much simpler and looks a lot better as well. We can completely ignore the fact that there is anything called a Node outside of the list:

    for word in words.iter():
        print(word) 

Notice that since the iter() method yields the data member of the node, our client code doesn't need to worry about that at all.