I understand that custom classes in Python are generally mutable. So in the example below, any changes done to the argument s in the function inc_age is reflected back at the calling section.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def inc_age(s):
s.age += 1
s1 = Student("Test",5)
inc_age(s1)
print(s1.age) # 6
I tried to implement linked list in Python using custom class as shown below:
class ListNode:
def __init__(self, data=0, next=None):
self.data = data
self.next = next
def next_node(L):
L = L.next
end = ListNode(3)
mid = ListNode(2,end)
beg = ListNode(1,mid)
next_node(beg)
print(beg.data) # 1
My question is why the change in object L in the function next_node not observed at the calling section.
L = L.nextchanges the local variableL, which is then discarded because you never do anything with it. Did you mean toreturn L?Studentobject but not forListNodeobject.