natureminded natureminded - 2 months ago 21
Python Question

How can I print all of the values of the nodes in my singly linked list using a while loop, or using the __iter__ magic method?

If I have created a linked list of nodes which have a

value
attribute, is there a way to print all
value
attributes for all nodes in the linked list using a while loop?

[Edit] Also, how might I invoke the iter magic method so that I can iterate and print over the linked list? How also might I create a method that allows for additions, at the beginning, end, or before or after a certain object?

(I apologize if there is something basic, conceptually, that I'm missing in my understanding)

Below is the code for the nodes and singly linked list I've got setup, and you'll see that I've printed each value for each node at the bottom. However, I wasn't sure if there was a simple way to print all values easily, rather than listing each one:

# node class
class Node(object):
def __init__(self, value):
self.value = value
self.next = None

# singly linked list class
class SinglyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None

linked_list = SinglyLinkedList()
linked_list.head = Node('Alice')
linked_list.head.next = Node('Chad')
linked_list.head.next.next = Node('Debra')

print linked_list.head.value, linked_list.head.next.value, linked_list.head.next.next.value
# is there a way to print all values for `linked_list` easily?


Thank you Stack Community for your help and for reading!

Answer

You can use a while loop, setting a variable to the head at first and the next node on each iteration:

node = linked_list.head
while node:
    print node.value
    node = node.next

A few other suggestions for your implementation:

1) Don't use list as a variable name. It's a sequence type in Python.

2) Don't forget to set tail!

3) If you want to be fancy, you can implement __iter__ on your linked list to make it iterable. You can also implement an add method so that it's easier to add new items to your list. Here's an example implementation:

class Node(object):
    def __init__(self, value):
        self.value = value
        self.next = None

class SinglyLinkedList(object):
    def __init__(self):
        self.head = None
        self.tail = None

    def __iter__(self):
        node = linked_list.head
        while node:
            yield node
            node = node.next

    def add(self, node):
        if self.head:
            self.tail.next = node
        else:
            self.head = node

        self.tail = node

linked_list = SinglyLinkedList()
linked_list.add(Node('Alice'))
linked_list.add(Node('Chad'))
linked_list.add(Node('Debra'))

print [node.value for node in linked_list]  # ['Alice', 'Chad', 'Debra']