Reputation: 13
I have a problem in Python:
I want to add a string to a list, but the last name is in the form of a string, is this even possible?
I already tried the exec() functions, but that gave me only errors:
ListA = ["a", "b"]
X = "ListA"
L = "c"
print(ListA)
{append to list A, without mentioning list a}
I want the output to be:
["a", "b", "c"]
is there a function like:
X.append(L)
to which, it appends to ListA?
Upvotes: 1
Views: 104
Reputation: 3564
ListA = ["a", "b"]
X = "ListA"
L = "c"
globals()[X].append(L)
print(ListA)
Upvotes: 1
Reputation: 823
You can eval
the list name and then append the value:
eval(X).append(L)
print(ListA) # ["a", "b", "c"]
Upvotes: 1