Puzzling difference between lists and tuples

Greg Ewing greg.ewing at canterbury.ac.nz
Sun Sep 20 19:57:20 EDT 2020


On 21/09/20 10:59 am, Avi Gross wrote:
>>>> a=tuple("first")
>>>> type(a)
> <class 'tuple'>
> 
> That seems more explicit than adding a trailing comma.

It doesn't do what you want, though:

 >>> a = tuple("first")
 >>> print(a)
('f', 'i', 'r', 's', 't')

If you really want to use tuple() to create a 1-tuple without
using a trailing comma, you can do it this way:

 >>> a = tuple(["first"])
 >>> print(a)
('first',)

But this costs you both a list creation and a tuple() call.
On my machine it seems to be about 17 times slower than using
a trailing comma:

 >>> timeit.repeat("tuple(['first'])")
[0.17746889099998953, 0.17687880599999062, 0.17687711000002082, 
0.1767632840000033, 0.17684489200001963]
 >>> timeit.repeat("('first',)")
[0.01173928899999055, 0.011569334000000708, 0.011588000000017473, 
0.011569761000032486, 0.011579383999958281]

-- 
Greg


More information about the Python-list mailing list