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?
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 totuple()
and make the tuple all at once. This will give you both the tuple you want and a way to make it cleanly.