0

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?

coccolith
  • 47
  • 8
  • 1
    Aren't tuples immutable? In that case, it makes sense that you can't change it. – M-Chen-3 Dec 08 '20 at 16:36
  • If the indices of `parameters` really is just a set of continuous integers from 0 to `nsize - 1`, consider using a list instead. `parameters = list(range(1,nsize+1))`. Then Mark Meyer's answer becomes simply `tuple(Experiment(x) for x in parameters)`. – chepner Dec 08 '20 at 16:47
  • Does this answer your question? [How to fix a : TypeError 'tuple' object does not support item assignment](https://stackoverflow.com/questions/19338209/how-to-fix-a-typeerror-tuple-object-does-not-support-item-assignment) – Tomerikoo Dec 08 '20 at 16:52

3 Answers3

5

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))
Mark
  • 90,562
  • 7
  • 108
  • 148
0

Tuple are immutable, you should consider changing it to a list.

SDTbone
  • 49
  • 1
  • 3
  • 6
0

Since tuples are immutable, you can convert tuples to something mutable, do you stuff and then convert it back to tuples using tuple () function