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?

3
  • 1
    Aren't tuples immutable? In that case, it makes sense that you can't change it. Commented Dec 8, 2020 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). Commented Dec 8, 2020 at 16:47
  • Does this answer your question? How to fix a : TypeError 'tuple' object does not support item assignment Commented Dec 8, 2020 at 16:52

3 Answers 3

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))
Sign up to request clarification or add additional context in comments.

1 Comment

This works great, thanks for the super quick reply!
0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.