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:
- How do I create variable variables?
- How can you dynamically create variables?
- Using a string variable as a variable name
Answered By - Timur Shtatland Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.