Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Emptying a list or dictionary for reuse

I have a script that looks like this

import tkinter as tk
from random import randint

a=[]
b=[]
c={}
d={}

def program():
    a.append(1)
    c[randint(10, 20)] = randint(0, 10) 
    do_something()
    do_something_else()

    print(a)
    print(b)
    print(c)
    print(d)
    print('done')

    return

def do_something():
    b.append(15)
    return

def do_something_else():
    d[randint(10, 20)] = randint(0, 10)
    return


root = tk.Tk()
tk.Button(root, text="Run", command=program).pack()
root.mainloop()

The problem here is clicking the button runs the function program() again with the previous values in the lists and dictionaries and so they are just appended. I want an empty dicts and lists everytime program()is called.

I created a function to do just that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def empty():
    global a,b,c,d
    a=[]
    b=[]
    c={}
    d={}
    return

Ive seen much talk about not using global in functions. What would be a neat way to achieve this?

>Solution :

Just make the variables local to program() and pass them around:

import tkinter as tk
from random import randint

def program():
    a=[]
    b=[]
    c={}
    d={}
    a.append(1)
    c[randint(10, 20)] = randint(0, 10) 
    do_something(b)
    do_something_else(d)

    print(a)
    print(b)
    print(c)
    print(d)
    print('done')


def do_something(b):
    b.append(15)


def do_something_else(d):
    d[randint(10, 20)] = randint(0, 10)


root = tk.Tk()
tk.Button(root, text="Run", command=program).pack()
root.mainloop()

Now each call to program() starts with new collections.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading