I have some code that generates two strings - digit_ and 'x', where x is an integer. My gut feeling is that this is a stupid question, but I can't find an answer online. I have variables called digit_1, digit_2 ... etc up to digit_9. How can I call the correct one of these without using a really long if/elif function? Is there a way of calling a variable from a concatenation of it's name? Sam
2 Answers
No, there isn't a good way to "create" variable names and access them.
However, you can just use a list, and index into it instead.
3 Comments
Xymostech
@Lattyware What are the good ways to do this? I've actually never seen this (although I fear for it being on this page, in case someone uses it in the wrong way).
abarnert
Or, if they're members of a class or an object,
getattr.Gareth Latty
@Xymostech StevenRumbalski & abarnert beat me to it. That is the best way of doing a bad thing (normally people try to do this with
exec(), which is the bad way).
something_1,something_2,...something_xyou always want a list. It's a common anti-pattern. Likewise withsomething_age,something_height, etc... you want a dictionary or a class.