Making the Linked List Iterable
Earlier, I mentioned that one limitation of our
LinkedList is that there’s no easy way to use it as an iterable—that is, we can’t use it in places where an iterable type is expected, such as in a
for loop. To mitigate this, we added a
.__repr__() method that returned a formatted string representation of the
LinkedList—but that’s really more useful in the context of debugging than anywhere else. To make our
LinkedList iterable so we can step through each
Node one by one, all we need to do is add a
Now we can say
while node is not None, yield the current
node and set the current
node to the next one. This special
yield keyword is similar to
return, except that it doesn’t stop execution of the current method once it’s reached.
In other articles, you might see traversal code like this wrapped inside a method called
traverse() or something similar. We can absolutely do that here, but it’s a bit more Pythonic if we take advantage of the
.__iter__() method provided by the language to make our list an iterable type.
Become a Member to join the conversation.