>
>
> > On the other hand, it might be an indication that a tuple is the wrong
> tool for the job.
>
maybe -- if I"m doing a lot of replacing, I likely would turn to a list --
but if you need an immutable, you need an immutable. I'm pretty sure I've
written code like:
temp = list(a_tuple)
temp[i] = new_value
a_tuple = tuple(temp)
and the OP's suggestion is buggy at the boundary:
In [204]: def replace1(tup, index, value):
...: return tup[:index] + (value,) + tup[index+1:]
...:
In [205]: tup
Out[205]: (1, 2, 3, 4, 5)
In [206]: replace1(tup, 5, 100)
Out[206]: (1, 2, 3, 4, 5, 100)
And converting to a list and back is actually. a tad faster:
In [209]: def replace1(tup, index, value):
...: return tup[:index] + (value,) + tup[index+1:]
...:
In [210]: def replace2(tup, index, value):
...: temp = list(tup)
...: temp[index] = value
...: return tuple(temp)
...:
In [211]: %timeit replace1(tup, 3, 100)
402 ns ± 7.19 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [212]: %timeit replace2(tup, 3, 100)
319 ns ± 12.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Not every one or two line function needs to be in the stdlib, but short
functions that are easy to get wrong are good candidates :-)
> As noted, a namedtuple DOES allow you to replace one component, and to do
> so by name rather than knowing its index, so possibly that would be a
> better choice here.
>
maybe, but namedtuple is a lot more awkward and heavyweight -- and slower:
In [225]: NTup = namedtuple('NTup', ('one', 'two', 'three', 'four', 'five'))
In [226]: ntup = NTup(1,2,3,4,5)
In [227]: %timeit ntup._replace(three=100)
1.16 µs ± 38.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
I would never recommend a namedtuple for a situation where a tuple is a
fine choice other the the lack of a replace method.
Frankly, now that dataclasses are built in to the stdlib, I'll bet we'll
see fewer uses of namedtuple. Yes, I know they are very different beasts,
but I suspect a lot of folks used namedtuples because they wanted a simple
data structure with a few attributes -- and didn't need it to be a tuple,
or immutable. I may be wrong, it's purely conjecture.
-CHB
--
Christopher Barker, PhD (Chris)
Python Language Consulting
- Teaching
- Scientific Software Development
- Desktop GUI and Web Development
- wxPython, numpy, scipy, Cython
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/IZYH5XPBTDYRPQVTOVBDMQDALCFPXLIJ/
Code of Conduct: http://python.org/psf/codeofconduct/