storm 1236
storm 1236

Reputation: 13

Python append string to list without mentioning list

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

Answers (3)

Aniket Bote
Aniket Bote

Reputation: 3564

ListA = ["a", "b"]

X = "ListA"

L = "c"

globals()[X].append(L)
print(ListA)

Upvotes: 1

Frank
Frank

Reputation: 154

If "ListA" is a global variable, you can do globals()[X].append(L)

Upvotes: 1

Juan Diego Garcia
Juan Diego Garcia

Reputation: 823

You can eval the list name and then append the value:

eval(X).append(L)
print(ListA)  # ["a", "b", "c"]

Upvotes: 1

Related Questions