what is the difference between tuple and list?

Harold Fellermann dadapapa at googlemail.com
Tue May 16 11:04:17 EDT 2006


The main difference is that lists are mutables while tuples are not.

Tuples are fine if you only want to group some objects (e.g. as a
return value) and access their members as in
>>> t = (1,2,3,4)
>>> t[2]
3

Lists give you a lot more flexibility, because they are mutable: you
can change the order of elements (e.g. sort), or delete or append items
(all that this is not possible for tuples). These features make lists
the primary data structures for stacks, queues, a.s.o.

So, whenever you want to change what objects are in your collection or
their ordering, use lists, otherwise, use tuples. Note, that this does
not mean, that the items themselves cannot be changed. You can
perfectly well change an object (e.g. dictionary) that resides in a
tuple:

>>> t = ({},)  # tuple with empty dict as its only item
>>> t[0]["foo"] = "bar"

But if you e.g. want to exchange, that dictionary by another, you need
to go for a list instead of a tuple.

Hope that made sense...

- harold -




More information about the Python-list mailing list