0

Working on a custom lists class in python like

class ListData:
        def __init__(self):
                 self.data = []

        def add(self, x):
                 self.data.append(x)

        def delete(self, x):
                 self.data.remove(x)

When testing, always return None :

from list import ListData

listdata = ListData()


mylist = [34, 32, 34, 89]
mylist = listdata.add(2)
mylist = listdata.add(5)

print mylist # Prints None
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
bobsr
  • 3,879
  • 8
  • 30
  • 37

2 Answers2

0

You're not returning anything from the add and delete methods, so assigning their return values to mylist leaves you with None. Get rid of the extra assignments and your code will work.

mylist = [34, 32, 34, 89]
listdata.add(2)
listdata.add(5)

print mylist

Alternatively you could modify the methods to return self, though there's not much value in doing so.

def add(self, x):
    self.data.append(x)
    return self

def delete(self, x):
    self.data.remove(x)
    return self
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

You can change your API to be able to print it as a list. you may read the following

Immutable vs Mutable types

class ListData:
        def __init__(self):
                 self.data = []

        def add(self, x):
                 self.data.append(x)

        def delete(self, x):
                 self.data.remove(x)

        def data(self):
            return self.data




a = ListData()
a.add(1)
a.add(2)
print a.data

will output:

[1, 2]

Community
  • 1
  • 1
0x90
  • 39,472
  • 36
  • 165
  • 245