[Tutor] tuples versus lists

Dave Kuhlman dkuhlman at rexx.com
Fri Sep 15 22:11:43 CEST 2006


On Thu, Sep 14, 2006 at 11:14:20PM -0700, Bob Gailer wrote:
> John Fouhy wrote:
> > Generally, you should use a tuple when you have different things that
> > you want to clump together to make one data structure.  Whereas you
> > should use a list when you have multiple things that are the same,
> > that you want to iterate over.
> >   
> Different perspective: tuples are immutable, lists are not. One may 
> change a list by various techniques; one may not change a tuple.
> 

Trying hard to be picky here ...

It's good to remember that, although you cannot change a tupble
itself, you can change the objects that the tuple references, *if*
they are mutable.  For example (in the ipython prompt):

    In [1]: d1 = {}
    In [2]: d2 = {}
    In [3]: t1 = (d1, d2)
    In [4]:
    In [4]: t1
    Out[4]: ({}, {})
    In [5]: t1[0]['name'] = 'dave'
    In [6]:
    In [6]: t1
    Out[6]: ({'name': 'dave'}, {})
    In [7]:

> tuples may be used as dictionary keys; lists may not

Good point.  A dictionary with tuples as keys can be used to
represent multi-dimensional, sparse  arrays.

> tuples are found on the right of % (formatting); lists are not

A list can be used on the right side of the formatting operator,
but python interprets it as a single object, not multiple objects
to be fed into the formatting specifiers.  So, for example, this
gives an error:

    In [7]: 'item 1: %s and item 2: %s' % [11, 22]
    ---------------------------------------------------------------------------
    exceptions.TypeError                                 Traceback (most recent call last)

    /home/dkuhlman/<ipython console>

    TypeError: not enough arguments for format string
    In [8]:

But, this does not:

    In [8]: 'item 1: %s' % [11, 22]
    Out[8]: 'item 1: [11, 22]'
    In [9]:

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list