How to add variable to another variable’s name [duplicate]
so I have a loop, and I want to call a variable for example name and add x from a loop to the end of the variable’s name, so it looks like name0. for example:
for x, var enumurate(something): name + x = something
Any time you think you need to do this, you should be using an array or dictionary, not dynamically-constructed variables.
You could achieve something like that but please don’t do it. Just don’t do it. Variable variable names are the first step on your road to hell.
I understand that it’s bad, but it’s neccesery for me, I save myself from repeating each line, any examples ?
No, I’m sure it’s not necessary. Please learn about data structures like list and dict . They will do what you want, but in a much cleaner way. Maybe you could enhance your question by describing why you think you need variable variable names?
1 Answer 1
What you ask is possible, but should not be done.
>>> foo = ['fee', 'fie', 'foe', 'fum'] >>> for i, val in enumerate(foo): . exec 'foo%s = %s' % (i, repr(val)) . >>> foo3 'fum' >>> foo[3] 'fum'
What you are asking for is a typical beginner error. Refering to the fourth item in foo as foo3 has no advantages over writing foo[3] . You can iterate over foo without having to know how many items it has. You can mutate foo if you like. You can refer to the last item in foo as foo[-1] without having to know it has four items. Also, the name foo3 is nonsensical. It tells the reader of the code nothing about why the items in foo are so important that they would need a name.
Using a string variable as a variable name [duplicate]
I have a variable with a string assigned to it and I want to define a new variable based on that string.
foo = "bar" foo = "something else" # What I actually want is: bar = "something else"
No you don’t. The reason you have to use exec is because locals() doesn’t support modifications. locals() doesn’t support modifications because it would make the implementation more complex and slower and is never a good idea
I landed on this post trying to find out how to assign instance variables for a class using a dictionary. If anybody else has the same problem, you can find a clean solution without exec here: stackoverflow.com/questions/8187082/…
3 Answers 3
You can use exec for that:
>>> foo = "bar" >>> exec(foo + " = 'something else'") >>> print bar something else >>>
Note use of exec / eval is considered poor practice. I have not met a single use case where it has been helpful, and there are usually better alternatives such as dict .
+100 what @jpp said. While this answer is useful and correct, if you’re writing something other than a one-off script, you can most likely use a dict .
You will be much happier using a dictionary instead:
my_data = <> foo = "hello" my_data[foo] = "goodbye" assert my_data["hello"] == "goodbye"
I’m glad to see the answer is still here. I think we can trust Stack Overflow readers to judge for themselves whether an answer suits their needs. This answer does not provide «variable variables,» it is true. But I guarantee you that 99% of the people looking for them will be happier to have found dictionaries.
It does not DIRECTLY answer the question, however, people might be asking that question while ignoring they can use a dictionary for the same purpose
Can we use variable in name of variable in python [duplicate]
I am trying to create a variable in python with prefix as list and then number which will be generated dynamically in the script. For example I am trying to have a list10 where list is the prefix and 10 is the number generated dynamically. In TCL we give like
Yes, the way to do this in Python and Tcl is not to use sequential variable names. It is a terrible practice since it turns data into code. Yes, tcl allows you to do it, but dict set mydict $i [list 4 5 6] is far better as are the Python answers below.
2 Answers 2
The pythonic way to do this would be to make a dictionary to store your lists with the generated names as the dictionary’s keys:
d = <> d['list1'] = [1, 2, 3] d['list2'] = ['a', 'b', 'c']
You can create keys like this:
key = 'list' + str(1) # or whatever number you are using dPython using variables in variable names = [your list]
Or if you don’t really need to know the names, store your lists in a list and retrieve them by index:
I think it is not solving purpose. Can I append in dict keys. Say I have declared dict key as dictPython using variables in variable names. I want to append in this. I am trying as dictPython using variables in variable names.append = value. But it is givng error
Please open a new question explaining what you really want to do and showing your code — the question that you asked has been answered.
You can use locals() , vars() , or globals() and inject your variable name there. For eg.
>>> list10 Traceback (most recent call last): File "", line 1, in NameError: name 'list10' is not defined >>> locals() , '__package__': None, 'x': [], '__name__': '__main__', '__doc__': None> >>> locals()['list10'] = [] >>> locals() , 'list10': [], '__package__': None, 'x': [], '__name__': '__main__', '__doc__': None> >>> list10 []
Generally, if you’re doing something like this, you’d probably be better off with using a dictionary to store the variable name and the value(s).
>>> my_lists = <> >>> my_lists['list10'] = []
And then when you want to look it up, you can .get() it if you want robustness against a variable name not existing, or directly accessing it if you’re going to guard against non-existence yourself.
>>> the_list_i_want = my_lists.get('list10') >>> the_list_i_want = my_lists['list10'] # Will raise a KeyError if it does not exist
How to use variable in variable name
How can I call variable play_level in the attributes of Character? The code I write is not working. Thanks!
3 Answers 3
Instead of that, try using a dictionary:
class Character(): def __init__(self): self.skillbylevel = < 10: 'aaa', 20: 'bbb', 30: 'ccc' >player_level = 20 hero = Character() print(hero.skillbylevel[player_level])
getattr should do this for you. It allows you to build a string, and fetch the attribute off the object with that name.
attribute_name = level_int(player_level) + "_skill" print(getattr(Character, attribute_name))
If attribute_name is not the name of an attribute on your class, then it will raise AttributeError just like it would if you called Character.not_an_attribute , so behaviorally it’s identical.
You can also override the default behaviour of rasining an exception by giving getattr a third argument;
getattr(Character, attribute_name, "No skill this level")
While you can set up your class that way, I think an easier, more readable way would be something like this:
#! /usr/bin/env python class Character(): def __init__(self, level): self.skill_level = level self.skills = < 10: 'aaa', 20: 'bbb', 30: 'ccc' >def set_skill_level(self, skill_level): self.skill_level = skill_level def get_skill_level(self): return "You are currently at skill level ".format(self.skill_level) def get_skill(self): return "Your skill is ".format(self.skills[self.skill_level]) if __name__ == "__main__": my_character = Character(20) print(my_character.get_skill_level()) print(my_character.get_skill())
Here, you are storing the relevant instance variables, the skill level and what skill pertains to that level, and providing class methods to interact with this data. I think using a dictionary to define the skills at each level is cleaner than defining a different instance variable for each skill because it offers you the flexibility of passing the skill list in as an argument to the class, or reading it from an external source, such as a database, file, etc.