Note that there are some explanatory texts on larger screens.

plurals
  1. POShell-style list generation or variable expression in Python?
    text
    copied!<p>----Complete Rephrasing----</p> <p>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.</p> <p>But I see that this is a awful approach. As I understand it now, I should do one of the following instead:</p> <ul> <li>Include embedded references in the class and thereby create a recursive data structure.</li> <li>Create a list of all of the instances, which is perhaps updated in the class <strong>init</strong> or when a new instance is made.</li> <li>Forget defining a new class in the first place and use a list of other objects.</li> </ul> <p>I hope I've got that straight. Thanks again for the advice.</p> <p>-----Original but edited generalized question-----</p> <p>Hello,</p> <p>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:</p> <pre><code>n=1 List_Of_X=[] while n &lt; 4: List_Of_X.append("x%s" % (n)) n += 1 </code></pre> <p>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? </p> <p>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. </p> <p>I get the feeling that either solutions are probably not the best practices but I appreciate all the help! Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload