Lists, Dictionaries and Tuples

by Nigel George

Lists, dictionaries and tuples are used to store collections of objects. They are differentiated from each other by the delimiter they use:

  • []. A list. E.g. ["one","two"]
  • {}. A dictionary. E.g. {1:"one", 2:"two"}
  • (). A tuple. E.g. ("one", 2)

Lists you should be very familiar with, as we all use lists daily. A dictionary is also straight forward—think of a regular dictionary where you have the word and then the meaning or definition of the word. In Python, the word is called a key and the definition a value.

Tuples are like lists, with a couple of differences.

Lists are designed to contain largely homogeneous data, much like in real life where you would have a shopping list or a to do list. By convention, Python list items should all be the same type (although Python doesn’t enforce this rule).

Tuples, on the other hand, are used to store heterogeneous data—("one", 2, [three]) is perfectly acceptable as a tuple, where it would be frowned upon as a list.

A single element tuple (singleton) is also written differently to a single element list:

lst = ["one"]  # 1 element list
tpl = ("one",) # 1 element tuple with trailing comma
               # to differentiate between
               # a plain string ("one") or a
               # functions parameter some_func("one")

Tuples, like strings, are immutable. Once they are created you can’t change them. Lists and dictionaries, however, are mutable and can be changed. Let me illustrate with some examples:

>>> lst = ["one"]     # Set up a list, tuple and dictionary
>>> tpl = ("one",)
>>> dict = {0:"one"}

>>> lst[0]            # All contain the same first element 'one'
>>> tpl[0]
>>> dict[0]
>>> lst[0] = "two"    # List is mutable (can be changed)
>>> lst
>>> dict[0] = "two"   # So is the dictionary
>>> dict
{0: 'two'}
>>> tpl[0] = "two"    # Tuple is immutable. Can't change! Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> str = "one"       # String is also immutable
>>> str[0] = "x"
Traceback (most recent call last): File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Here’s a screenshot of the exercise:

One last point on tuples vs. lists—tuples are often used for homogeneous data that the programmer doesn’t want changed by accident. So, if you have a list of items that should not be changed, it can be a good idea to use a tuple instead of a list.

Lesson Resources

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}