generate a modified copy of a tuple
<p>I know I can't modify a tuple and I've seen ways to create a tuple from another one concatenating parts of the original manually like <a href="http://stackoverflow.com/questions/11458239/python-changing-value-in-a-tuple">here</a>.</p>

<p>But wonder whether there has emerged some pythonic way to 'modify' a tuple by implicitly creating a new one like</p>

<pre><code>&gt;&gt;&gt; source_tuple = ('this', 'is', 'the', 'old', 'tuple')
&gt;&gt;&gt; new_tuple = source_tuple.replace(3, 'new')
&gt;&gt;&gt; new_tuple
('this', 'is', 'the', 'new', 'tuple')
</code></pre>

<p>A possible implementation could look like this but I'm looking for a <em>built in</em> solution:</p>

<pre><code>def replace_at(source, index, value):
    if isinstance(source, tuple):
        return source[:index] + (value,) + source[index + 1:]
    elif isinstance(source, list):
        return source[:index] + [value,] + source[index + 1:]
    else:
        explode()
</code></pre>

<p>it's not much work to implement such a functionality but like the <code>Enum</code> has demonstrated it's sometimes better to have an implementation everyone uses..</p>

<p><strong>Edit</strong>: my goal is <em>not</em> to replace the source tuple. I know I could use lists but even in this case I would make a copy first. So I'm really just looking for a way to create a modified copy.</p>

<p>You could use some kind of comprehension:</p>

<pre><code>source_tuple = ('this', 'is', 'the', 'old', 'tuple')
new_tuple = tuple((value if x != 3 else 'new'
                   for x, value in enumerate(source_tuple)))
# ('this', 'is', 'the', 'new', 'tuple')
</code></pre>

<p>This is rather idotic in this case but gives you an idea of the general concept. Better use a <strong>list</strong>, though, after all, you can change the values index-based here.</p>

python tuples immutability