Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize empty list?

Tags:

python

Every time the input s comes from the form; the list is initialized again. How do I change the code to append each new s to the list?

Thank you.

class Test(webapp.RequestHandler):
    def get(self):

        s = self.request.get('sentence')
        list = []                                   
        list.append(s)                      
        htmlcode1 = HTML.table(list)        
like image 626
Zeynel Avatar asked Oct 22 '10 23:10

Zeynel


2 Answers

I'm not sure what the context of your code is, but this should work:

class Test(webapp.RequestHandler):
    def get(self):
        s = self.request.get('sentence')
        try:
            self.myList.append(s)
        except NameError:
            self.myList= [s]
        htmlcode1 = HTML.table(self.myList)

This makes list an instance variable so it'll stick around. The problem is that list might not exist the first time we try to use it, so in this case we need to initialize it.

Actually, looking at this post, this might be cleaner code:

class Test(webapp.RequestHandler):
    def get(self):
        s = self.request.get('sentence')
        if not hasattr(self, 'myList'):
            self.myList = []
        self.myList.append(s)
        htmlcode1 = HTML.table(self.myList)

[Edit:] The above isn't working for some reason, so try this:

class Test(webapp.RequestHandler):
    myList = []
    def get(self):
        s = self.request.get('sentence')
        self.myList.append(s)
        htmlcode1 = HTML.table(self.myList)
like image 176
dln385 Avatar answered Sep 20 '22 17:09

dln385


You could make the list a member variable of the object and then only update it when get() is called:

class Test(webapp.RequestHandler):
    def __init__(self, *p, **kw): # or whatever parameters this takes
        webapp.RequestHandler.__init__(self, *p, **kw)
        self.list = []

    def get(self):
        s = self.request.get('sentence')
        self.list.append(s)                      
        htmlcode1 = HTML.table(self.list)        
like image 33
sth Avatar answered Sep 24 '22 17:09

sth