Iterate through Linked List in Python, makes no sense (HashMaps)

Hi guys,

Currently doing the exercise on Hash Maps in Python, located here:

[Hash Maps | Codecademy](https://www.codecademy.com/paths/computer-science/tracks/cspath-cs-
102/modules/hash-maps/projects/blossom)

Basically, when it comes to the part of implementing separate chaining in the hash map, we end up with an array of Linked List objects, and somehow the instructor uses a for loop to iterate through the Linked List?

Like when we are updating the assign method, we get our index via the hash and compress methods, and we store the Linked List object at that array index in a variable called list_at_index.

This I am assuming is a Linked List object, so how can we use a for loop to just iterate through each node in the list?

Thanks.

Michael

Hello! To answer your question: you might want to take a look inside the file linked_list.py accessible from the workspace, which contains the definition for the Linked List class used in the exercise. The definition contains the following:

def __iter__(self):
    current_node = self.head_node
    while(current_node):
      yield current_node.get_value()
      current_node = current_node.get_next_node()

The iter dunder method is part of the python Iterator protocol. Defining this method allows the user to perform things like for loops over a custom object (and control what actually happens in the loop itself).

More information here!

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.