Thursday, July 21, 2022

[FIXED] How do I append to a list when the name of the list lies within a string?

Issue

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")

Solution

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:



Answered By - Timur Shtatland
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.