2

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

1
  • 2
    If you find yourself doing something_1, something_2,... something_x you always want a list. It's a common anti-pattern. Likewise with something_age, something_height, etc... you want a dictionary or a class. Commented Nov 28, 2012 at 20:16

2 Answers 2

7

The cleanest way is to put the variables into a list or a dictionary, and then access them by index or by name.

Sign up to request clarification or add additional context in comments.

Comments

1

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

@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).
Or, if they're members of a class or an object, getattr.
@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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.