Ad hoc lists vs ad hoc tuples
Terry Reedy
tjreedy at udel.edu
Wed Jan 27 17:15:10 EST 2010
On 1/27/2010 12:32 PM, Antoine Pitrou wrote:
> Le Wed, 27 Jan 2010 02:20:53 -0800, Floris Bruynooghe a écrit :
>>
>> Is a list or tuple better or more efficient in these situations?
>
> Tuples are faster to allocate (they are allocated in one single step) and
> quite a bit smaller too.
> In some situations, in Python 2.7 and 3.1, they can also be ignored by
> the garbage collector, yielding faster collections.
>
> (not to mention that they are hashable, which can be useful)
Constant tuples (a tuple whose members are all seen as constants by the
compiler) are now pre-compiled and constructed once and put into the
code object as such rather than re-constructed with each run of the code.
>>> from dis import dis
>>> def l(): return [1,2,3]
>>> def t(): return 1,2,3
>>> dis(l)
1 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 BUILD_LIST 3
12 RETURN_VALUE
>>> dis(t)
1 0 LOAD_CONST 4 ((1, 2, 3))
3 RETURN_VALUE
>>> # 3.1
Terry Jan Reedy
More information about the Python-list
mailing list