lists and tuples
Jack Diederich
jack at performancedrivers.com
Thu Jun 26 14:35:59 EDT 2003
On Thu, Jun 26, 2003 at 03:18:17PM +0200, Gerrit Holl wrote:
> Hi,
>
> one of the things I have never understood in Python was why tuples
> exist. There is a FAQ entry about this:
>
> http://www.python.org/cgi-bin/faqw.py?req=show&file=faq06.015.htp
>
> This says:
> > This is done so that tuples can be immutable while lists are mutable.
> >
> > Immutable tuples are useful in situations where you need to pass a few items to a function and don't want the function to modify the tuple; for example,
> >
> > point1 = (120, 140)
> > point2 = (200, 300)
> > record(point1, point2)
> > draw(point1, point2)
> >
> > You don't want to have to think about what would happen if record() changed the coordinates -- it can't, because the tuples are immutable.
Check the python-dev archives for something like 'tuples vs lists'
The main difference is conceptual and not technical (although there are
technical differences too). Lists are meant to hold a flexible array
of homogeneous data, a list of numbers or Foos. Tuples are meant as structs,
they hold related heterogeneous data like a record in a database.
tuple/
('jane', 'doe', 30) # first/last/age
list/
[('jane', 'doe', 30), ('john', 'smith', 21)] # list of tuples
so using tuples as dictionaries keys makes sense, you are indexing on a
unique set (in this case name & age). Indexing people makes a lot of sense,
indexing on a list of people makes less sense.
That's the short version, browse the archives for a much longer discussion.
[and do that _before_ posting to this one *wink*]
-jack
More information about the Python-list
mailing list