suggestions for using tuples instead of list (or vice versa)
Peter Hansen
peter at engcorp.com
Thu Apr 29 09:08:25 EDT 2004
Thorsten Kampe wrote:
> I found out that I am rarely using tuples and almost always lists
> because of the more flexible usability of lists (methods, etc.)
>
> To my knowledge, the only fundamental difference between tuples and
> lists is that tuples are immutable, so if this is correct, than list
> are a superset of tuples, meaning lists can do everything tuples can
> do and more.
Only tuples can be used as dictionary keys.
> Is there any advantage for using tuples? Are they "faster"? Consume
> less memory?
Not appreciably so in most cases. Certainly not enough to
be a factor in choosing which to use except perhaps in
very rare edge cases.
> When is it better to use tuples instead of lists and when
> better to use lists instead of tuples?
The canonical answer (which some disagree with) is that you
should use tuples when you have a collection of different
types of items, such as a 'struct' in C would have. Use
lists any other time you want a simple sequential collection
of items.
Use a list for effectively everything else, unless you need
an immutable (tuple) for a dictionary key.
One description of how to look at this that I've found helpful
is something along the lines of "if you can take a slice of
the data and consider it in the same way as the original,
then you should use a list". For example, if you have a set
of fifteen objects over which you plan to iterate, you can
just as well iterate over the first five. If, however, you
have a tuple of (year, month, day, hour, minute, second),
taking the first four items is quite a different thing than
taking all six of them.
-Peter
More information about the Python-list
mailing list