As you can see, tuples share many of their properties and methods with lists. However, they differ in one very important area: lists are mutable, while tuples are immutable (like strings). It is not possible to alter tuple elements once a tuple has been created; the only way to accomplish this is to create a new tuple containing the new elements.
Finally, you can iterate through a tuple in much the same way
as a list - with the "for" loop.
>>> pasta
('macaroni', 'spaghetti', 'lasagne', 'fettucine', 'tagliatelle', 'rigatoni')
>>> for x in pasta:
... print "I like", x
...
I like macaroni
I like spaghetti
I like lasagne
I like fettucine
I like tagliatelle
I like rigatoni
>>>
At this point, you're probably wondering why you need tuples
when you already have lists to contend with. It's pretty simple: the built-in immutability of tuples provides an automatic defense against program code that attempts to change tuple elements, thereby ensuring the integrity of the data contained within this structure. As we progress through this tutorial, you'll see examples of where this might come in useful.{mospagebreak title=Keys To The Kingdom} One of the significant features of lists and tuples is that the values stored within them can only be accessed via a numerical index. The implication of this is obvious: if you need to access an element of the list or tuple, you need to first know its exact location in the structure. Since this can get complicated with large lists, Python offers you a simpler way to access list values, using a data structure known as a dictionary.
Dictionaries are similar to lists and tuples, in that they allow you to group related elements together. However, where lists and tuples use an index to identify and locate specific elements or groups of elements, dictionaries use keywords ("keys") to accomplish the same task. In fact, Python dictionaries are the equivalent of Perl hashes or PHP associative arrays.
Let's take a look at a simple example to demonstrate this:
Dictionaries are typically enclosed within curly braces, and
each element within a dictionary consists of a "key" and a "value" associated with that key, separated from each other by a colon (:). Since every value in the dictionary is associated with a specific key, you can reference a specific value via its key.
As you can see, the elements in a dictionary are not placed
in a specific sequence, as with lists and tuples; new elements are assigned to random places within the dictionary space.
It should be noted that keys and values in a dictionary need not be restricted to strings alone - numbers and tuples serve equally well as keys (which must be immutable),
while values could include strings, numbers, and even other
dictionaries, lists or tuples (isn't it cool how Python allows you to nest one data structure within another?)