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>If you're thinking of swapping values on the fly, then a <code>list</code> is the more appropriate data structure; as we already know tuples are <em>immutable</em>.</p>

<p>On another note, if you're looking for a <em>swap-value</em> logic in a <code>tuple</code>, you can have a look at <a href="https://docs.python.org/3.4/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields" rel="nofollow"><code>collections.namedtuple</code></a> which has a <code>_replace</code> method.</p>

<blockquote>
  <p>They can be used wherever regular tuples are used</p>
</blockquote>

<pre><code>&gt;&gt;&gt; source_tuple = ('this', 'is', 'the', 'old', 'tuple')

&gt;&gt;&gt; Factory = namedtuple('Factory', range(5), rename=True)

&gt;&gt;&gt; source_tuple = Factory(*source_tuple)

&gt;&gt;&gt; source_tuple
Factory(_0='this', _1='is', _2='the', _3='old', _4='tuple')

&gt;&gt;&gt; new_tuple = source_tuple._replace(_3='new')

&gt;&gt;&gt; new_tuple
Factory(_0='this', _1='is', _2='the', _3='new', _4='tuple')
</code></pre>

<p>Well that doesn't look too elegant. I still suggest you use a <code>list</code> instead.</p>

python tuples immutability