473,609 Members | 1,943 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Create variable for each iteration of a for loop

9 New Member
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
5 42158
bvdet
2,851 Recognized Expert Moderator Specialist
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
dwblas
626 Recognized Expert Contributor
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
2,851 Recognized Expert Moderator Specialist
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
Dave Elfers
9 New Member
Yes, that is exactly what I was looking for. Thank you much!!
Nov 16 '10 #5
ray214
1 New Member
After you get all the variable var1, var2, var3, how would you store them in a list?
May 7 '19 #6

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

Similar topics

4
2706
by: Christopher Benson-Manica | last post by:
I have a situation something like this: int foo; for( foo=bar() ; foo <= bar()+1 ; foo++ ) { if( !baz(foo) ) break; /* do stuff with foo */ } The idea is that the loop happens at most twice - once for foo=bar(), and once
3
8089
by: paulw | last post by:
Hi I have a question: main() { static int i; printf("%d\n",i); // should I see see 0 or 5 ??? for (i=5;i<=15;i++) {...} // What's the meaning of static variable in
2
1832
by: Mike Mac | last post by:
Hello all, I have a loop and would like to create a new textbox on each iteration of the loop. The code below only generates one textbox no matter how many times the loop loops! Any insight would be greatly appreciated. int over = 25; int down = 0; for (int i = theEmail.Attachments.Count; i > 0; i--)
7
9763
by: david | last post by:
I try to use "for" loop to assign textbox control ID to a textbox variable in server side codebehind for a web form. But I met some problem. What I want to do is solving the following-like code by a loop: static code: txtQ1.Text = ds.Tables("mmsSpecRecord").Rows(0)("Q1") txtQ2.Text = ds.Tables("mmsSpecRecord").Rows(0)("Q2") ..... txtQ10.Text = ds.Tables("mmsSpecRecord").Rows(0)("Q10") where Q1, .. Q10 are field name of a table; and...
0
3695
by: shaikm | last post by:
Hi, I have problem passing variable in a FOR LOOP. Following is my code. Any help much appreciated. ZS -- Procedure teta has two parameters l and q , l is the feature table and q is the quality table create or replace procedure teta(l varchar2,q varchar2) is -- a string variable vst is declared to store the SQL statement
1
2922
by: Bassey | last post by:
Hi, This is my code. create trigger addDnsRecord_staticIphost on staticIPHost for insert, update as begin declare @EthMac varchar(255)
2
7740
by: Jim | last post by:
Hello: I have an Access database with a table with sequentially numbered fields (e.g., Q10_1, Q10_2, Q10_3, etc. What I want to do is cycle through the variables to set them to values. What I want to do is ___________________________________________ For MaxVariables = 1 To 11 Step 1
9
4607
by: praveena mani | last post by:
create procedure view_select (coll int(11)) begin declare x int; declare y int; set x=0; select count(*) into y from s_details where college_code=coll; while(x<y) do select day_number,title,first_name,middle_name,last_name, date_of_birth,e_mail,ref_number,
12
2677
by: poornimamprabhu | last post by:
Hi there, suppose i have piece of code like main() { int i,j; for(i=0;i<10;i++){ int k = i; printf("%d %p = *%d\n",i,&k,k); }
0
8145
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8588
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8410
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7030
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5526
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4037
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2541
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1690
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1407
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.