1

I've got multiple lists:

    list_1 = []
    list_2 = []
    list_3 = []

And I've got the following string, which depending on the circumstances will correspond to one of the lists above:

    x = 'list_2'

How do I go about appending to the list by using the string? Is there any way I can do something along the lines of:

    'value of x'.append("Whatever")
Mike
  • 67
  • 3

3 Answers3

3

Use a dictionary of lists. Do not use eval if you can avoid it (it is dangerous), and yours is a classic case where you can avoid it.

dct = {'list_1': [],
       'list_2': [],
       'list_3': [],}

x = 'list_2'
print(dct[x])
# []

SEE ALSO:

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
-1
>>> list_1 = []
>>> list_2 = []
>>> list_3 = []
>>> x = 'list_2'
>>> eval(x).append("whatever")
>>> list_2
['whatever']
user10864
  • 1
  • 1
  • 1
    Please include an explanation with your answer to help readers understand how this works, and solves the problem. You can click the edit button at the bottom of your answer to add an explanation. Additionally, you may find it beneficial reading [how to answer](https://stackoverflow.com/help/how-to-answer). – Freddy Mcloughlan Jun 16 '22 at 04:31
-1

you can use eval

list_1 = [1,2,3]
list_2 = [4,5,6]
list_3 = [7,8,9]

x = 'list_2'
print(eval(x))

Output:

[4, 5, 6]
Gam
  • 318
  • 2
  • 9