Tuple vs List: Whats the difference?

Dave Baum Dave.Baum at motorola.com
Wed Jul 11 21:07:32 CEST 2007


In article <1184177195.569916.184770 at 22g2000hsm.googlegroups.com>,
 Shafik <shafik23 at gmail.com> wrote:

> Hello folks,
> 
> I am an experienced programmer, but very new to python (2 days). I
> wanted to ask: what exactly is the difference between a tuple and a
> list? I'm sure there are some, but I can't seem to find a situation
> where I can use one but not the other.

Lists and tuples are both sequences, and can be used interchangeably in 
many situations.  The big difference is that lists are mutable (can be 
modified), and tuples are immutable (cannot be modified).  Lists also 
have a richer API (for example the index and count methods).

If you are going to need to change the contents of the sequence 
(appending, removing, altering a value, etc), then use a list.

If you require the sequence to be immutable (such as being used as the 
key in a dictionary), then use a tuple.

In general, tuples should be a little more efficient than lists.  
However, altering a list is more efficient than creating a new tuple, so 
"always prefer tuples" does not necessarily lead to a faster overall 
program.  Unless performance is critical, I wouldn't worry about this 
factor.

IMHO, a more important reason to prefer tuples is that since they are 
immutable, you don't have to worry about side effects.  If you call a 
function and pass it a list, you have no guarantee that the list won't 
be changed during the function call.  With tuples, any attempt to change 
the tuple will raise an exception.  If it is important to the caller 
that the sequence remain unchanged, then a tuple is a safer 
representation for that sequence.

Dave



More information about the Python-list mailing list