Search code examples
pythonassignment-operator

Python: Indexing the left side and right side of an assignment


I'm trying to do something simple like the following

for k in range(0,2)

outsetk = Reader(FileName='/dir/outset-'+str(k)+'.q')

to generate the following

outset0 = Reader(FileName='/dir/outset-'+str(0)+'.q')
outset1 = Reader(FileName='/dir/outset-'+str(1)+'.q')
outset2 = Reader(FileName='/dir/outset-'+str(2)+'.q')

where Reader is some predefined function with only one input. I know the right side of the assignment is correct but I'm not sure how to do the left side.


Solution

  • Try using a dictionary to hold the results. Something like this:

    outsets = {}
    
    for k in range(0, 3):
        outsets[k] = Reader(FileName='/dir/outset-' + str(k) + '.q')
    

    Then you would access outset0 like so:

    outsets[0] # equivalent to your outset0
    

    You could also do something like this to get the same names mentioned in your example:

    outsets = {}
    name = 'outset{}'
    
    for k in range(0, 3):
        outsets[name.format(k)] = Reader(FileName='/dir/outset-' + str(k) + '.q')
    

    To access outset0 you would use outsets['outset0']

    If you wanted to use a list instead, try something like this:

    outsets = []
    
    for k in range(0, 3):
         outsets.append(Reader(FileName='/dir/outset-' + str(k) + '.q')
    

    Then you would access outset0 the same way:

     outsets[0] # equivalent to your outset0