3

I want to define a global list and append a list to it. I am getting a list (i[0]) by some on click event and appended that to mnum_list. Now i want create a global list and append that mnum_list to it. Any idea how to do this?

def OnClick(self, event):                                       
    name = event.GetEventObject().GetLabelText()
    cursor= self.conn.execute("SELECT * FROM ELEMENT where SYMBOL==?", (name,))
    elements = cursor.fetchall()
    print elements
    cursor= self.conn.execute("SELECT ATOMIC_NUMBER FROM ELEMENT where SYMBOL = ?", (name,))
    numbers = cursor.fetchone()[0]
    print numbers
    atomicnumber = numbers
    cursor= self.conn.execute("SELECT MOL_NUMBER FROM LINK where ELEMENT_NUMBER = ?", (atomicnumber,))
    mnumbers = cursor.fetchall()
    print mnumbers
    mnum_list = []
    for i in mnumbers:
         mnum_list.append(i[0])
    print mnum_list
anon_particle
  • 337
  • 1
  • 4
  • 16
  • 1
    Possible duplicate of [Using global variables in a function other than the one that created them](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) – Mike Scotty Jun 20 '17 at 06:37
  • On a side note: I personally consider global variables a design flaw and I would avoid them at all cost if possible. – Mike Scotty Jun 20 '17 at 06:39
  • @mpf82 No, your comment is acting as if global variables are inherently wrong; They aren't. There are perfectly valid use cases for global variables, such as "constant" values. It's when you start trying to use global variables as state that you start getting spaghetti code. – Christian Dean Jun 20 '17 at 06:43
  • @mpf82: the OP is trying to manipulate a global. They can just do so without having to know how to use `global`, because there is *no assignment to the global name*. – Martijn Pieters Jun 20 '17 at 06:43
  • If you have a global list (`some_global_list = []` at the module level), then just reference it to append to it: `some_global_list.append(mnum_list)`. Mutating a global is that simple. – Martijn Pieters Jun 20 '17 at 06:49

2 Answers2

1

There is no need in global statement if there is no assignment, just:

def foo(x):
    sublist = range(x)
    glist.append(sublist)

and in case of extension:

def foo(x):
    sublist = range(x)
    glist.extend(sublist)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Dimgold
  • 2,748
  • 5
  • 26
  • 49
0

You can declare it on the file/module level like: my_global_list = list()

and when you want to append to it inside a function you can use the global keyword. The global keyword tells python to look for the global variable.

global my_global_list

my_global_list.append()

user3732361
  • 377
  • 8
  • 13