I am new to Python. I tried many ways but never get to understand why the following code changed node_j.
Then I stumped on some codes which worked by adding "or []", as in the second version attached. I still do to know why it worked. Any insight is appreciated.
class Node():
def __init__(self, data, itslist=[]):
self.data = data
self.itslist = itslist
def extend_list(self, node):
self.itslist += [node]
def __str__(self):
string = self.data
for item in self.itslist:
string += '->' + item.data
return string
node_i = Node('I')
node_j = Node('J')
print(node_j) #print is: J
node_i.extend_list(node_j)
print(node_j) #print is: J->J, why did node_j add itself to itslist)?
The following code works but I do not know why it works.
def __init__(self, data, itslist=[]):
self.data = data
self.itslist = itslist or [] # what does"or []" do?
def extend_list(self, node):
self.itslist += [node]
def __str__(self):
string = self.data
for item in self.itslist:
string += '->' + item.data
return string
node_i = Node('I')
node_j = Node('J')
print(node_j) #print is: J
node_i.extend_list(node_j)
print(node_j) #print is: J, node_j no change
Thanks!