Sequence Types - Tuple

Indices and tables

Tuple

MUTABILITY: Immutable

A tuple is an ordered sequence (i.e. a collection) of zero or more arbitrary Python objects (i.e. object references. The items need not all be the same type and you can nest other collection types if desired. Tuples are often referred to as N-tuple’s, depending on how many items are in the collection.

Since tuples are immutable, you can’t modify individual elements after creation without creating a new object. If this is required, use a list instead. Although this feature points out an advantage of lists over tuples, tuples are faster and more memory efficient than lists and lists can’t be used where a dynamically sized object is prohibited.

Tip

Many people subscribe to the following idiom:

  • Use tuples for heterogeneous data sets (like structs) that you deal with as a coherent unit.
  • Use lists for homogeneous data sets where you deal with each item in the list individually.

Although, nothing in Python requires, or strictly enforces, this.

An example of this is having a list of pixels, where each pixel is a 3-tuple of RGB color values.

Tuples can be constructed in a variety of ways:

  • Using parenthesis (). For example:

    To create a tuple with 0 items:

    >>> foo = ()
    >>> foo
    ()
    

    To create a tuple with 1 item a trailing comma is required:

    >>> foo = (1,)
    >>> foo
    (1,)
    

    To create a tuple of 2 or more items:

    >>> foo = (1, 2, 3)
    >>> foo
    (1, 2, 3)
    

    Note

    Except for the empty tuple case, it is the comma that makes it a tuple, not the parenthesis. In fact, except for the empty tuple case, or, to avoid syntactic ambiguity, the parenthesis aren’t even required! For example:

    >>> a = (5)
    >>> a
    5
    >>> type(a)
    int
    >>> b = (5,)
    >>> b
    (5,)
    >>> type(b)
    tuple
    >>> c = 5, 6, 7
    >>> c
    (5,6,7)
    >>> type(c)
    tuple
    
  • Using the tuple constructor, which allows you to do several things:

    With no arguments, it creates an empty tuple:

    >>> foo = tuple()
    >>> foo
    ()
    

    When passed something it can iterate over, it builds a tuple from each of the items (this is a form of type conversion):

    >>> foo = tuple('a1b2c3')
    >>> foo
    ('a', '1', 'b', '2', 'c', '3')
    
    >>> bar = [1, 2, 3]
    >>> bar
    [1, 2, 3]
    >>> type(bar)
    list
    >>> baz = tuple(bar)
    >>> baz
    (1, 2, 3)
    >>> type(baz)
    tuple
    

    When passed a tuple, this is one way of shallow-copy ing the tuple:

    >>> foo = (1, 2, 3)
    >>> bar = tuple(foo)
    >>> bar
    (1, 2, 3)
    

Tuple Specific Methods

There are no tuple specific methods.

Try it!

Try creating the following objects:

  • An empty tuple.
  • A tuple of 1 item.
  • A tuple of 2 items.
  • A tuple from the string, “abc”.
  • A tuple of a string and another tuple.
  • A tuple of 2 tuples.