0

This might be a really stupid question but is it possible to keep a local empty list updated in this instance:

def voeg_vriendschap_toe(sn, naam_persoon1, naam_persoon2):
    relaties = []
    count_variabel = 0
    aanwezig_persoon1 = False
    aanwezig_persoon2 = False
    uitvoeren = True
    for i in relaties:
        if((i[0] == naam_persoon1) and (i[1] == naam_persoon2)):
            uitvoeren = False
    while ((len(sn) > count_variabel) and ((aanwezig_persoon1 == False) or (aanwezig_persoon2 == False)) and (uitvoeren == True)):
        if (sn[count_variabel] == naam_persoon1):
            aanwezig_persoon1 = True
        if (sn[count_variabel] == naam_persoon2):
            aanwezig_persoon2 = True
        count_variabel += 1
    if ((aanwezig_persoon1 == True) and (aanwezig_persoon2 == True)):
        sn.append([naam_persoon1, naam_persoon2])
        sn.append([naam_persoon2, naam_persoon1])
        relaties.append([naam_persoon1, naam_persoon2])
        relaties.append([naam_persoon2, naam_persoon1])
        return sn
    else:
        return sn

I want relaties to be updated after the appends and not be an empty list again when the function is called multiple times.

So in case voeg_vriendschap_toe() is called once, and relaties is updated to [[1,2], [2,1]]. However if it's called again it becomes an empty list again rather than keeping its value. Is it possible to have it keep its value without using a global variable?

LLScheme
  • 73
  • 7
  • 2
    Make it a class instead, in which `relaties` is an *instance attribute* and keeps state with the instantiated object…?! – deceze Dec 03 '19 at 12:04

1 Answers1

0

If you don't want to use a class, a way to obtain what you want is to use a mutable default argument:

def voeg_vriendschap_toe(sn, naam_persoon1, naam_persoon2, relaties = []):
    count_variabel = 0
    ...

This way, relaties will only be evaluated to [] once at the function definition.

You can have a look at Default Parameter Values in Python and Least Astonishment” and the Mutable Default Argument for more details.

Note that, though, depending on your usage case, using a class might be better.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50