How to fill a tuple with a for loop

955 views Asked by At

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?

3

There are 3 answers

1
Mark On BEST ANSWER

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))
0
Just don't be user123 On

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

0
SDTbone On

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