Well, as Trufa has already shown, there are basically two ways to replace a tuple element with a given index. Either convert the tuple to a list, replace the element and convert it back, or build a new tuple by concatenation.
In [1]: def replace_at_index1(tup, ix, val): ...: lst = list(tup) ...: lst[ix] = val ...: return tuple(lst) ...: In [2]: def replace_at_index2(tup, ix, val): ...: return tup[:ix] + (val,) + tup[ix+1:] ...:
So which method is better, i.e. faster?
It turns out that for short tuples (in Python 3.3), concatenation is faster!
In [3]: d = tuple(range(10)) In [4]: %timeit replace_at_index1(d, 5, 99) 1000000 loops, best of 3: 872 ns per loop In [5]: %timeit replace_at_index2(d, 5, 99) 1000000 loops, best of 3: 642 ns per loop
However, if we look at longer tuples, list conversion is a way:
In [6]: k = tuple(range(1000)) In [7]: %timeit replace_at_index1(k, 500, 99) 100000 loops, best of 3: 9.08 µs per loop In [8]: %timeit replace_at_index2(k, 500, 99) 100000 loops, best of 3: 10.1 µs per loop
For very long tuples, list conversion is much better!
In [9]: m = tuple(range(1000000)) In [10]: %timeit replace_at_index1(m, 500000, 99) 10 loops, best of 3: 26.6 ms per loop In [11]: %timeit replace_at_index2(m, 500000, 99) 10 loops, best of 3: 35.9 ms per loop
In addition, the performance of the concatenation method depends on the index in which we replace the element. For a list method, the index does not matter.
In [12]: %timeit replace_at_index1(m, 900000, 99) 10 loops, best of 3: 26.6 ms per loop In [13]: %timeit replace_at_index2(m, 900000, 99) 10 loops, best of 3: 49.2 ms per loop
So: if your tuple is short, cut and join. If it is long, do the list conversion!