0

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!

John A.
  • 1
  • 2
  • 1
    See the dupe. Here though, `or []` fixes the problem since if the default is used, the parameter will hold an empty (falsey) list, which means `itslist or []` will always evaluate to its second argument, `[]`, which is a new list. Without that, all uses of the default argument share the same exact list. – Carcigenicate Sep 04 '21 at 18:20
  • Thanks, Carcigenicate. I thought the itslist is already default to [ ] in def __init__(self, data, itslist=[ ]). When node_j = Node('J'), node_j has [ ] as itslist. – John A. Sep 04 '21 at 18:45

0 Answers0