

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 6
click for more info
Not enough gems
Cost: 6 gems
1: Linked Lists
incomplete
2: Linked List vs. List
incomplete
3: Generators
incomplete
4: Iterating
incomplete
5: Add to Tail
incomplete
6: Add to Head
incomplete
7: Linked List Queue
incomplete
8: Remove from Head
incomplete
9: Linked List Queue Quiz
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Even though iterating with linked lists kinda sucks compared to the simplicity of arrays (normal lists), we've got to do it. Although the implementation is more complex and slow, we can still make it easy for users of our class by providing an __iter__ method. If __iter__ is a generator function, Python can use it to drive a for loop over our class.
The LinkedList class is a wrapper class that uses the Node class we already wrote.
No other node points to the linked list's head (first) node, so the LinkedList class itself needs to keep track of it. We'll use the term head and tail like this:
head node -> node -> node -> node -> tail node
The direction of flow above might feel opposite to what you're used to with a Queue, but it's really the same. Above I'm using arrows to show which nodes are pointing to which other nodes. In a future lesson when we implement a Queue using a LinkedList, we'll add elements to the tail and remove elements from the head.
We need to change which node is the next to be yielded, but the set_next method of the Node class changes which is the next to be pointed to – don't use it!
By overriding the __iter__ method, Python will allow us to use a for loop to iterate over the linked list:
from node import Node
ll = LinkedList()
ll.head = Node("first")
ll.head.next = Node("second")
ll.head.next.next = Node("third")
for node in ll:
print(node.val)