[Python-Dev] Re: lists v. tuples (original) (raw)

Kevin J. Butler python-kbutler@sabaydi.com
Thu, 13 Mar 2003 13:09:01 -0700


*Guido van Rossum * guido@python.org mailto:guido%40python.org //

Tuples are for heterogeneous data, list are for homogeneous data. Only if you include both null cases:

Homo-/heterogeneity is orthogonal to the primary benefits of lists (mutability) and of tuples (fixed order/length).

Else why can you do list( (1, "two", 3.0) ) and tuple( [x, y, z] ) ?

Tuples are not read-only lists. It just happens that "tuple( sequence )" is the most easy & obvious (and thus right?) way to spell "immutable sequence".

Stop reading whenever you're convinced. ;-) (not about mutability, but about homo/heterogeneity)

There are three (mostly) independent characteristics of tuples (in most to least important order, by frequency of use, IMO):

The important characteristics of lists are also independent of each other (again, IMO on the order):

It turns out that fixed-length sequences are often useful for heterogeneous data, and that most sequences that require mutability are homogeneous.

Examples from the standard library (found by grep '= (' and grep '= [' ):

# homogeneous tuple - homogeneity, fixed order, and fixed length are 

all required # CVS says Guido wrote/imported this. ;-) whrandom.py: self._seed = (x or 1, y or 1, z or 1)

# homogeneous tuple - homogeneity is required - all entries must be 

'types' # suitable for passing to 'isinstance( A, typesTuple )', which (needlessly?) requires a tuple to avoid # possibly recursive general sequences types.py: StringTypes = (StringType, UnicodeType)

# heterogeneous list of values of all basic types (we need to be 

able to copy all types of values) # this could be a tuple, but neither immutability, nor fixed length, nor fixed order are needed, so it makes more sense as a list # CVS blames Guido here, too, in version 1.1. ;-) copy.py: l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'], {'abc': 'ABC'}, (), [], {}]

Other homogeneous tuples (may benefit from mutability, but require fixed-length/order):

Other heterogeneous lists (homogeneous lists of base-class instances blah-blah-blah):

Must-be-stubborn-if-you-got-this-far-ly y'rs ;-)

kb