0

I want each variable put into this function to then become the name of its own list.

def listy(x, insert):
    listend = isinstance(x, list)
    if listend:
        x.append(insert)
    else:
        x = []
        x.append(insert)
    print(x)

listy("xyz", "neutral")
listy("xyz", "happy")

When I do this, though, it overwrites the previous list (ends up with the list just reading "happy" instead of "neutral", "happy"). How do I get it to append if that word is already the name of a list?

UriGroup
  • 19
  • 1

2 Answers2

0

Here this works for the example you gave. It uses dictionaries.

def listy(x, insert):
    varName[x].append(insert)
    return varName
varName = {"xyz":[]}
x = listy("xyz", "neutral")
y=listy("xyz", "happy")
print(y)

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

it overwrites the previous list ..

The previous list is not overwritten. The list created inside the function listy is auto destroyed by garbage collector. You are simply creating a new temporary list in second function call listy("xyz", "happy"), which will be destroted again. You need to put x in global context.

You can rewrite the function this way:

def listy(x, insert):
    listend = isinstance(x, list)
    if listend:
        x.append(insert)
    else:
        x = []
        x.append(insert)
    print(x)
    return x

x = listy("xyz", "neutral")
x = listy(x, "happy")

You seem to have confusion about references and objects. In python, everything is an object. A name like x is just a reference to an object. There is no way x in the second function call can refer to ["neutral"] created and destroyed in the first function call.

Silentroar
  • 71
  • 1
  • 9