Nelson's log

tuple vs list

One small thing in Python3 that continues to confound me is how dict.values, dict.keys, and zip all don’t return real collections but instead iterables. That means you have to wrap them first in a tuple or list if you want to array index the output. It’s not a huge deal, but it’s a nuisance.

So which is better? Tuple or list? Tuple should be in theory, because it’s immutable it should be a little more efficient. Seems to be that way in practice too.

$ python3 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.266 usec per loop
$ python3 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.331 usec per loop

$ python2 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.227 usec per loop
$ python2 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.256 usec per loop

(You know, every time I do a timeit on python2 vs python3, python3 is measurably slower. Some of that is due to Unicode but I don’t think that’s all of it.)