0

I have an function for clearing a list and a the ame time copying it. I need the copy outside of the function, but when I use "global" there is only an empty list. The list is not empty inside of the function, only outside. What can I do?

k_grade_list = []
g_grade_list = []

def average():
    g_grade = input_one.get()
    k_grade = input_two.get()
    wert = int(input_three.get())

    g_grade_list.extend(g_grade.split(','))
    g_grade_avg = float((summe(g_grade_list) / len(g_grade_list)))

    k_grade_list.extend(k_grade.split(','))
    k_grade_avg = float((summe(k_grade_list) / len(k_grade_list)))

    wert = wert / 100

    return (k_grade_avg * wert) + (g_grade_avg * (1 - wert))


def list_clear():
    global ks_grade_list
    ks_grade_list = k_grade_list
    global gs_grade_list
    gs_grade_list = g_grade_list

    k_grade_list.clear()
    g_grade_list.clear()
Barmar
  • 741,623
  • 53
  • 500
  • 612
Gümmi
  • 3
  • 2
  • You're making them empty with `clear()`. Note that you're emptying both `ks_grade_list` and `k_grade_list`, since both variables are references to the same list. – Barmar May 22 '20 at 19:55
  • 1
    "at the same time copying it". You're not copying anything. – Barmar May 22 '20 at 19:56
  • How can I fix this? Is there any possibility for not making both lists empty? @Barmar – Gümmi May 22 '20 at 20:03
  • 1
    See https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – Barmar May 22 '20 at 20:04
  • I don't understand what you're trying to do. What is the purpose of `ks_grade_list` and `gs_grade_list`? You never use them anywhere. – Barmar May 22 '20 at 20:06

2 Answers2

1

You have to define the list outside of the function and reference it using global like this:

k_grade_list = []
g_grade_list = []

// Do stuff with the list

def list_clear():
    global k_grade_list, g_grade_list

    k_grade_list.clear()
    g_grade_list.clear()
Vincent
  • 482
  • 4
  • 15
0

Don't use clear(), since that modifies the list that both variables reference. Just assign empty lists to the variables, this will make new lists.

def list_clear():
    global ks_grade_list
    ks_grade_list = k_grade_list
    global gs_grade_list
    gs_grade_list = g_grade_list

    k_grade_list = []
    g_grade_list = []
Barmar
  • 741,623
  • 53
  • 500
  • 612