Python Forum
Creating a variable in for loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a variable in for loop
#1
Hi all, this is what I have so far:

for i in range(len(self.my_tuple)):
            "self.furniture{0}".format(i) == self.my_tuple[i]
As you can see this doesn´t work and I cannot find out how to fix it. I want to create a new variable in each for loop but not sure what´s the syntax of it. Thanks.
Reply
#2
Why do you want to do this? It's a poor programming idea. What's wrong with using self.my_tuple[3] instead of self.furniture3 ?
Or perhaps you could do self.furniture = self.my_tuple and then use self.furniture[3], which is better than self.furniture3
Reply
#3
First of all, you should iterate over the list, not the indexes of the list, as shown here

Second, you shouldn't be turning a list or tuple into separate variables with a number at the end of their name. Keep it in a list to retain the power of the list. self.furniture = list(my_tuple)

Finally, when you do want to assign attributes to an object, use setattr:

for key, value in new_attrs.items():    # looping through a dict
    setattr(self, key, value)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
@Gribouillis

I need it for my dict(), there is no way to do it like you have described. Finally it should look like this:

self.dict_crates["self.furniture{0}".format(i)] = self.my_tuple[i]
Can you help me with that?
Reply
#5
What do you need help with? That code already works:
>>> class Spam:
...   def __init__(self):
...     self.dict_crates = {}
...     self.my_tuple = (5, 7, 3, 5, 1)
...   def foo(self):
...     for i in range(5):
...       self.dict_crates["self.furniture{0}".format(i)] = self.my_tuple[i]
...
>>> x = Spam()
>>> x.foo()
>>> x.dict_crates
{'self.furniture0': 5, 'self.furniture1': 7, 'self.furniture2': 3, 'self.furniture3': 5, 'self.furniture4': 1}
Reply
#6
@nilamo yes this works, but except making an item in a dictionary with specific value (tuple in this case) I also want to create a variable with the same name as a key in dict() is and add an specific image into it. Something like this:

for i in range(len(self.coords_tuple)):
    "self.furniture{0}".format(i) = self.canvas.create_image(self.coords_tuple[i][0], self.coords_tuple[i][1], anchor=NW, image=self.crate_image)
*self.coords_tuple is just a couple like (x,y), not important for this.

And this part: "self.furniture{0}".format(i) doesn´t work here.
Reply
#7
Again, furniture0, furniture1, furniture2 is a bad idea. You should keep it as a list.

self.furniture = []
for x, y in self.coords_tuple:   # again, loop through the object, not the indexes
    self.furniture.append(self.canvas.create_image(x, y, anchor = NW, image = self.create_image))
Now you can access them as self.furniture[0], self.furniture[1], self.furniture[2], ...
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
@ichabod801 ok, this seems clear, but how do I recognize now which key in my dictionary is related to specific item from this list? That´s why did I want to keep name of keys and name of variables the same, to make it simple when working with them.

Example: when working with a key "self.furniture0" I also want to work with self.furniture[0] and so on..
Reply
#9
You can put it all in the list:

self.furniture = []
for coords, crate in zip(self.coords_tuple, self.my_tuple):
    data = {'image': self.canvas.create_image(x, y, anchor = NW, image = self.create_image)}
    data['crate'] = crate
    self.furniture.append(data)
The you can access the two parts with self.furniture[2]['image'] and self.furniture[2]['crate']. You could also make a tuple of the two things, and append that. The you would access with self.furniture[2][0] and self.furnitures[2][1].
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#10
If the value of a dict is related to the value in a list, then those two values should be kept together, instead of separate.

So instead of a dict of {"furnature0": "canvas"}, and a list of ["furnature"], just have one variable keeping track of both.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable definitions inside loop / could be better? gugarciap 2 430 Jan-09-2024, 11:11 PM
Last Post: deanhystad
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,679 Nov-07-2023, 09:49 AM
Last Post: buran
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,569 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  loop (create variable where name is dependent on another variable) brianhclo 1 1,133 Aug-05-2022, 07:46 AM
Last Post: bowlofred
  Creating a loop with dynamic variables instead of hardcoded values FugaziRocks 3 1,477 Jul-27-2022, 08:50 PM
Last Post: rob101
  Multiple Loop Statements in a Variable Dexty 1 1,198 May-23-2022, 08:53 AM
Last Post: bowlofred
Big Grin Variable flag vs code outside of for loop?(Disregard) cubangt 2 1,166 Mar-16-2022, 08:54 PM
Last Post: cubangt
  How to save specific variable in for loop in to the database? ilknurg 1 1,142 Mar-09-2022, 10:32 PM
Last Post: cubangt
  How to add for loop values in variable paulo79 1 1,439 Mar-09-2022, 07:20 PM
Last Post: deanhystad
  Using Excel Cell As A Variable In A Loop knight2000 7 4,090 Aug-25-2021, 12:43 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020