0

I am trying to create list of list using different functions inside the class by calling an constructor array but it is giving one list

I want to specifically use build and build1 both the functions

class Sample:
   def __init__(self):
        self.add = list()

   def build(self,name):
        self.add.append(name)

   def build1(self,loc):
        self.add.append(loc)


s = Sample()
a1 = ["mohan,ps","gandhi,as"]
for a in a1:
    split_values = a.split(",")
    s.build(split_values[0])
    s.build1(split_values[1])

print s.add

Output

['mohan', 'ps', 'gandhi', 'as']

expected output:

[['mohan', 'ps'],['gandhi', 'as']]

How to get results as expected output

1 Answers1

0

You can try this.

class Sample:
   def __init__(self):
        self.add = list()

   def build(self,name):
        self.add.append(name)

   def build1(self,loc):
        self.add[-1].append(loc)     #Use negative index to append.


s = Sample()
a1 = ["mohan,ps","gandhi,as"]
for a in a1:
    split_values = a.split(",")
    s.build([split_values[0]])
    s.build1(split_values[1])

print s.add

Output:

[['mohan', 'ps'], ['gandhi', 'as']]
Rakesh
  • 81,458
  • 17
  • 76
  • 113