0

I'm trying to understand the core ideas of Python and I've come across to a nice article that explains passing the parameter reference to an object. For instance;

def add_to_list(list_to_add, value):
  list_to_add.append(value)

will be able to change the original list_to_add parameter while;

def change_list(list_to_add):
  list_to_add = [1, 2, 3, 5]

won't do anything.

I am currently writing a basic linked list print function where it is simply like;

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

root = Node(2, Node(3, Node(4, Node(5, Node(6)))))

def print_list(root):
  while root:
    print root.val,
    root = root.next
  print ''

And you've guessed it right. It didn't change the root's value. Now my question is how come this happens. Is it because the python classes are immutable?

Ali
  • 5,338
  • 12
  • 55
  • 78

2 Answers2

4

Python classes certainly aren't immutable. You can change them pretty much as you like (with some corner-cases involving either extension types or slots).

However, what you do here is you define a module-level (global) variable root, and then a parameter-name root within print_list.

Invoking print_list(root) and then assigning something to root will NOT change the module-level global!

If you want that (you shouldn't want that, but that's a different discussion about avoiding global variables), you'd have to declare root inside print_list to be global

def print_list():
    global root
    ...

And then you don't need the parameter.

AGAIN: Don't do this!!!

If you'd used a tool like pylint to check your code, it should have warned you that the parameter name "root" shadows a module-global name "root".

deets
  • 6,285
  • 29
  • 28
1

It is simple:

obj.do_something()

operates on the passed object, possibly modifying it (such as list_to_add.append()), while

obj = something_other

discards the reference to the old object and uses a different one.

Changes on an object will (of course) be visible to "other" users of the object, while a re-assignment only affects the place where it is redefined.

glglgl
  • 89,107
  • 13
  • 149
  • 217