—-Complete Rephrasing—-
I was working on a new class where each instance was essentially sequential and linked. I had thought, in a very shell scripty way, that I could define a function to compile a list of all of these instances if I named them systematically. Then I could do what I wanted in the first place, which was navigate through the sequence in some way.
But I see that this is a awful approach. As I understand it now, I should do one of the following instead:
- Include embedded references in the class and thereby create a recursive data structure.
- Create a list of all of the instances, which is perhaps updated in the class init or when a new instance is made.
- Forget defining a new class in the first place and use a list of other objects.
I hope I’ve got that straight. Thanks again for the advice.
—–Original but edited generalized question—–
Hello,
I’m relatively new to Python and I find myself always wanted to generate a list of existing objects of some kind. Say I had three variables named x# where # is a number from 1 to 3. The sort of code I feel tempted to write would be something like:
n=1
List_Of_X=[]
while n < 4:
List_Of_X.append("x%s" % (n))
n += 1
But then of course I end up with a list of strings rather than variables. So, is there any way to ‘express’ the variables corresponding to the strings? Or better yet, create a list of variables in the first place?
Edit: The crux was not specifying a list manually – I wanted somehow to automate that. It seems from the answers below that I can use my admittedly crummy method above to generate a list of strings, then use the eval() function to express them. Or, use a somewhat complex method of generating a list of objects in the first place.
I get the feeling that either solutions are probably not the best practices but I appreciate all the help! Thanks.
I think you first need to understand that there are no variables in Python. There are only references to objects. So it is a mistake to even think about “creating variables”. They don’t exist.