list vs. tuple [Re: len() should always return something]
Terry Reedy
tjreedy at udel.edu
Fri Jul 24 16:43:17 EDT 2009
Steven D'Aprano wrote:
> On Fri, 24 Jul 2009 15:03:29 -0400, Roy Smith wrote:
>
>> In article <mailman.3674.1248461573.8015.python-list at python.org>,
>> Terry Reedy <tjreedy at udel.edu> wrote:
>>
>>> Better: if isinstance(x, (int, float, complex)):
>> I never noticed this before, but it seems odd that the second argument
>> to isinstance() should be a tuple. Using the normal arguments made
>> about tuples vs. lists, it seems like a list would be the right data
>> structure here.
I ignore the 'normal arguments' and it seems that Guido or the designer
of isinstance did so here too. Fortunately. Practicality beats
'purity', especially misguided purity.
> What would be the point of using a list? You're never going to sort it,
> or append items to it, or otherwise mutate it. You build it, pass it to a
> function which doesn't modify it in any fashion, then it gets garbage
> collected.
>
>
>> I suppose a set would be even more right, but (I'm
>> pretty sure) isinstance() predates sets.
>
> Yes.
>
> [steve at sylar ~]$ python1.5
> Python 1.5.2 (#1, Apr 1 2009, 22:55:54) [GCC 4.1.2 20070925 (Red Hat
> 4.1.2-27)] on linux2
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>> isinstance
> <built-in function isinstance>
>>>> set
> Traceback (innermost last):
> File "<stdin>", line 1, in ?
> NameError: set
>
>
>
>> I'm curious why a tuple was chosen.
>
> Tuples are smaller and faster to build than lists -- they're the most
> lightweight sequence type in Python. You don't need all the extra
> functionality of lists, so why go to the time and effort of building a
> list?
In fact, constant tuples can be and now are compiled as constants:
>>> dis(compile('(1,2,3)','','eval'))
1 0 LOAD_CONST 3 ((1, 2, 3))
3 RETURN_VALUE
>>> dis(compile('[1,2,3]','','eval'))
1 0 LOAD_CONST 0 (1)
3 LOAD_CONST 1 (2)
6 LOAD_CONST 2 (3)
9 BUILD_LIST 3
12 RETURN_VALUE
Internally, even a frozenset is more complicated than a tuple since it
still needs a hash table, which is overkill for something that will be
linearly scanned exactly once.
tjr
More information about the Python-list
mailing list