pythonpython-collections

How to fill a tuple with a for loop


I am trying to fill a tuple with named tuples using a for loop.

The example code below works:

import collections

Experiment = collections.namedtuple('Experiment', ['parameter', ])

nsize = 3

parameters = {}
for n in range(0, nsize):
    parameters[n] = n +1
   

experiments = (
        Experiment(parameter = parameters[0]),   
        Experiment(parameter = parameters[1]),
        Experiment(parameter = parameters[2]),)

However, I would like to replace the last section with a for loop:

for n in range(0, nsize):
    experiments[n] = Experiment(parameter = parameters[n])

Which gives the error:

TypeError: 'tuple' object does not support item assignment

Any ideas?


Solution

  • Tuples are immutable, so you can't modify them after creating them. If you need to modify the data structure, you'll need to use a list.

    However, instead of using a for loop, you can pass a generator expression to tuple() and make the tuple all at once. This will give you both the tuple you want and a way to make it cleanly.

    import collections
    
    Experiment = collections.namedtuple('Experiment', ['parameter', ])
    
    nsize = 3
    
    parameters = {}
    for n in range(0, nsize):
        parameters[n] = n + 1
        
    expirements = tuple(Experiment(parameter = parameters[n]) for n in range(nsize))
    # (Experiment(parameter=1), Experiment(parameter=2), Experiment(parameter=3))