Here`s the code I wrote for insertion sort of a linked list:
def insertion_sort_by_rating(self):
sorted = None
current_node = self.head
while current_node:
next_node = current_node.next
sorted = sorted_insert(sorted, current_node)
current_node = next_node
self.head = sorted
node = self.head
nodes = []
while node:
nodes.append(str(node.data))
node = node.next
nodes.append("None")
return " -> ".join(nodes)
Where sorted_insert function is defined as follows:
def sorted_insert(head, new_node):
if head is None or head.data.rating >= new_node.data.rating:
new_node.next = head
head = new_node
else:
current_node = head
while (current_node.next is not None and
current_node.next.data.rating < new_node.data.rating):
current_node = current_node.next
pass
new_node.next = current_node.next
current_node.next = new_node
return head
Let`s focus on this fragment:
while current_node:
next_node = current_node.next
sorted = sorted_insert(sorted, current_node)
current_node = next_node
Why does sorted_insert function modify the current_node, so I can't just rewrite the above by assigning current_node to current_node.next right away after the function call? Here's what I mean:
while current_node:
sorted = sorted_insert(sorted, current_node)
current_node = current_node.next
current_node is not passed by reference in Python, so the above code should've been equivalent to the previous snipped, since sorted = sorted_insert(sorted, current_node), as I understand, can't affect the current_node.
So in which cases are variables in Python pass by reference, like here, and when are they pass by value?