Python custom list class initialization Consider the class AB below that is to be used as a simple customized list of A objects for lookup operations.

Can this code be improved to avoid instantiating AB with an empty list [] (i.e., perhaps modify __add__ in some way)?

class A():
    def __init__(self, arg):
        self.arg = arg

class AB():
    def __init__(self, list):
        self.list = list

    def __add__(self, other):
        return AB(self.list + [other])

ab = AB([])
ab += A(1)
ab += A(2)
Sure, you can play with the default argument value:

class AB:
    def __init__(self, data=None):
        self.data = data if data is not None else []

    def __add__(self, other):
        return AB(self.data + [other.arg])


Other notes:


list is a bad variable name as it is shadowing the built-in list keyword
remove redundant parentheses after the class name


Demo:

In [1]: ab = AB()

In [2]: ab += A(1)

In [3]: ab += A(2)

In [4]: print(ab.data)
[&lt;__main__.A instance at 0x10afb14d0&gt;, &lt;__main__.A instance at 0x10afa0998&gt;]