""" linked_list.py An example of a linked list in python : -> -> -> None To avoid confusion, here I'll refer to Python's built-in list as an "array". Jim Mahoney | cs.bennington.college | MIT License | March 2021 """ class Node: """ A node in a linked list. """ def __init__(self, name): self.name = name self.next = None def __str__(self): return "Node({})".format(self.name) def nodes_to_str(node): """ Given the first node, return the whole linked list as a string. """ # (Here I'm doing this with an explicit loop, # but this could also be done will with recursion.) result = '[' while node: result += str(node.name) + ', ' node = node.next return result + ']' def array_to_nodes(array): """ Given a python array, return the first node of a linked list. """ previous = None for element in array: this = Node(element) if previous: previous.next = this else: root = this previous = this return root def main(): numbers = [1, 2, 3, 4] linkedlist = array_to_nodes(numbers) print(nodes_to_str(linkedlist)) main()