Lists and Tuples

Joe Francia usenet at soraia.com
Fri Dec 5 04:02:13 EST 2003


Jeff Wagner wrote:
> I've spent most of the day playing around with lists and tuples to get a really good grasp on what
> you can do with them. I am still left with a question and that is, when should you choose a list or
> a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
> than just that.  Everything I tried with a list worked the same with a tuple. So, what's the
> difference and why choose one over the other?
> 

According to the Python FAQ:

------------------------------------------------------------------------
4.15   Why are there separate tuple and list data types?

Lists and tuples, while similar in many respects, are generally used in 
fundamentally different ways. Tuples can be thought of as being similar 
to Pascal records or C structs; they're small collections of related 
data which may be of different types which are operated on as a group. 
For example, a Cartesian coordinate is appropriately represented as a 
tuple of two or three numbers.

Lists, on the other hand, are more like arrays in other languages. They 
tend to hold a varying number of objects all of which have the same type 
and which are operated on one-by-one. For example, os.listdir('.') 
returns a list of strings representing the files in the current 
directory. Functions which operate on this output would generally not 
break if you added another file or two to the directory.

Tuples are immutable, meaning that once a tuple has been created, you 
can't replace any of its elements with a new value. Lists are mutable, 
meaning that you can always change a list's elements. Only immutable 
elements can be used as dictionary keys, and hence only tuples and not 
lists can be used as keys.

http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types
------------------------------------------------------------------------

Of course, this information will prevent neither flame wars, nor you 
from using them how you wish (within the boundaries of the language). 
However you choose to use them, just be clear and consistent.

Peace,
Joe




More information about the Python-list mailing list