Create variable for each iteration of a for loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dave Elfers
    New Member
    • Aug 2010
    • 9

    Create variable for each iteration of a for loop

    Hello, I am using a for loop to iterate through an array and need to assign each iteration to a new variable, such as

    Code:
    arr = ['bread', 'milk', 'cheese']
    for i in arr:
        print i
    but instead of printing i, I want the for lopp to assign each iteration to a unique variable, so that when the for loop completes

    Code:
    var1 = 'bread' 
    var2 = 'milk'
    var3 = 'cheese'
    I will use these variables later on in the script. I will not always know how many items are in the array and need the script to generate a new variable for each iteration. Any ideas?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    One way is to encapsulate the variables in an object.
    Code:
    class Vars(object):
        
        def __init__(self, *args):
            for i, value in enumerate(args):
                setattr(self, "var%s" % (i), value)
    
        def get(self):
            return self.__dict__
    
    obj = Vars("milk", "bread", "cheese")
    print obj.get()
    Output: >>> {'var1': 'bread', 'var0': 'milk', 'var2': 'cheese'}

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      You already have that capability with a list. No alteration necessary:
      Code:
      a_list = ['bread', 'milk', 'cheese']
      print a_list[1]  ## instead of var2
      
      for ctr in len(a_list):
          print ctr, a_list[ctr]

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        I think he is really wanting this:
        Code:
        >>> for i, value in enumerate(["milk", "bread", "cheese"]):
        ... 	exec "var%s=value" % (i)
        ... 	
        >>> var1
        'bread'
        >>>

        Comment

        • Dave Elfers
          New Member
          • Aug 2010
          • 9

          #5
          Yes, that is exactly what I was looking for. Thank you much!!

          Comment

          • ray214
            New Member
            • May 2019
            • 1

            #6
            After you get all the variable var1, var2, var3, how would you store them in a list?

            Comment

            Working...