0

Suppose I have the following function:

 def function3(start, end):
    """Read MO information."""
    config_found = False
    var = []
    for line in v['molecular orbital primitive coefficients']:
        if line.strip() == end:
            config_found = False
        elif config_found:
            i = line.rstrip()
            var.append(i)
        elif line.strip() == start:
            config_found = True
    var1 = [elem.strip() for elem in var]
    var2 = var1[1:-1]
    var3 = np.array([line.split() for line in var2])
    var3 = np.asarray([list(map(float, item)) for item in var3])
    return var3

And suppose I store its output in variables like so:

    monumber1=function3('1','2')
    monumber2=function3('2','3')
    monumber3=function3('3','4')

etc.

Is there a way for me to execute this function a set number of times and store the output in a set number of variables without manually setting the variable name and function arguments every time? Maybe using a for loop? This is my attempt, but I'm struggling to make it functional:

 for i in xrange(70):
    monumber[x] = function3([i],[i+1])

Thank you!

1
  • Don't use dynamic variables, use a container like a list or a dict Commented Aug 1, 2017 at 22:08

2 Answers 2

2

The problem is your use of square brackets. Here is code that should work:

monumber = [] # make it an empty list
for i in xrange(70):
    monumber.append(function3(str(i),str(i+1))) # you had string integers, so cast

For the more Pythonic one-liner, you can use a list comprehension:

monumber = [function3(str(i),str(i+1)) for i in xrange(70)]

Now that the monumber variable has been created, I can access the element at any given index i using the syntax monumber[i]. Some examples:

first = monumber[0] # gets the first element of monumber
last = monumber[-1] # gets the last index of monumber
for i in xrange(10,20): # starts at i = 10 and ends at i = 19
    print(monumber[i])  # print the i-th element of monumber
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, that worked perfectly! Can I ask you another question? How can I store each output in an individual variable? For instance, how can I access monumber[1] specifically?
Remember that Python is 0-based, so monumber[0] is the first element of monumber. To access any given element, you use the exact syntax you mentioned: monumber[i] accesses the element of monumber at index i. I'll update my answer with some examples
Oh, I see! Thank you so much!
0

You've almost got it. Except you should use i on the left hand side, too:

monumber[i] = function3([i],[i+1])

Now, this is the basic idea, but the code will only work if monumber is already a list with enough elements, otherwise an IndexError will occur.

Instead of creating a list and filling it with placeholders in advance, we can dynamically append new values to it:

monumber = []
for i in xrange(70):
    monumber.append(function3([i],[i+1]))

Another problem is that you seem to be confusing different types of arguments that your function works with. In the function body, it looks like start and end are strings, but in your code, you give to lists with one integer each. Without changing the function, you can do:

monumber = []
for i in xrange(70):
    monumber.append(function3(str(i),str(i+1)))

1 Comment

The square brackets seem incorrect, though. In OP's example, the parameters of function3 are strings ('1', '2', etc.). I think you should cast i and i+1 to strings instead of making 1-element lists (i.e., str(i) and str(i+1) instead of [i] and [i+1])

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.