PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

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

 July 21, 2022     append, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing