Is there a bulit-in way to create variabe names without writing them explicitly?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jory R Ferrell
    New Member
    • Jul 2011
    • 62

    Is there a bulit-in way to create variabe names without writing them explicitly?

    I'm using Python 3.2.
    For instance, can I create several lists in a loop and assign each one a name created by a function?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You can using built-in function eval().

    Comment

    • Jory R Ferrell
      New Member
      • Jul 2011
      • 62

      #3
      Ok...lol...I just found that a little while ago but the way it was written I didn't completely understand it. Got it working now...thanks!

      Comment

      • Glenton
        Recognized Expert Contributor
        • Nov 2008
        • 391

        #4
        Often a good way to do it (depending what you're trying to achieve) is to create a dictionary before the loop and then use whatever loop variable you want as the key for the dictionary. This is generally better than using eval IMHO. You also don't need to have a string as the key but can have any immutable type Eg an integer or a tuple.

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          I agree with Glenton that using eval is not the best solution.

          Comment

          • Jory R Ferrell
            New Member
            • Jul 2011
            • 62

            #6
            Yeh...after doing a little more research I found that Eval() poses a security risk. Besides that, the dictionary is less complicated.

            Comment

            Working...