By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,594 Members | 3,680 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,594 IT Pros & Developers. It's quick & easy.

Create variable for each iteration of a for loop

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

Expand|Select|Wrap|Line Numbers
  1. arr = ['bread', 'milk', 'cheese']
  2. for i in arr:
  3.     print i
  4.  
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

Expand|Select|Wrap|Line Numbers
  1. var1 = 'bread' 
  2. var2 = 'milk'
  3. var3 = 'cheese' 
  4.  
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?
Nov 15 '10 #1

✓ answered by bvdet

I think he is really wanting this:
Expand|Select|Wrap|Line Numbers
  1. >>> for i, value in enumerate(["milk", "bread", "cheese"]):
  2. ...     exec "var%s=value" % (i)
  3. ...     
  4. >>> var1
  5. 'bread'
  6. >>> 

Share this Question
Share on Google+
5 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
One way is to encapsulate the variables in an object.
Expand|Select|Wrap|Line Numbers
  1. class Vars(object):
  2.  
  3.     def __init__(self, *args):
  4.         for i, value in enumerate(args):
  5.             setattr(self, "var%s" % (i), value)
  6.  
  7.     def get(self):
  8.         return self.__dict__
  9.  
  10. obj = Vars("milk", "bread", "cheese")
  11. print obj.get()
Output: >>> {'var1': 'bread', 'var0': 'milk', 'var2': 'cheese'}
Nov 15 '10 #2

Expert 100+
P: 621
You already have that capability with a list. No alteration necessary:
Expand|Select|Wrap|Line Numbers
  1. a_list = ['bread', 'milk', 'cheese']
  2. print a_list[1]  ## instead of var2
  3.  
  4. for ctr in len(a_list):
  5.     print ctr, a_list[ctr] 
Nov 15 '10 #3

bvdet
Expert Mod 2.5K+
P: 2,851
I think he is really wanting this:
Expand|Select|Wrap|Line Numbers
  1. >>> for i, value in enumerate(["milk", "bread", "cheese"]):
  2. ...     exec "var%s=value" % (i)
  3. ...     
  4. >>> var1
  5. 'bread'
  6. >>> 
Nov 15 '10 #4

P: 9
Yes, that is exactly what I was looking for. Thank you much!!
Nov 16 '10 #5

P: 1
After you get all the variable var1, var2, var3, how would you store them in a list?
May 7 '19 #6

Post your reply

Sign in to post your reply or Sign up for a free account.