Python tuples

  1. Python tuples are just some values separated by commas:

    a_tuple = 123, 'abc', 456
    
  2. A tuple can also be surrounded by parentheses

    a_tuple = (123, 'abc', 456)
    
  3. Elements of a tuple can be accessed in the same way as with lists:

    >>> a_tuple[2]
    456
    
  4. But, whereas lists are mutable (you can change one or more elements of a list), tuples are not. Compare:

    >>> a_tuple = 123, 'abc', 456
    >>> a_tuple
    (123, 'abc', 456)
    >>> a_tuple[2]
    456
    >>> a_tuple[2] = 789
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'tuple' object does not support item assignment
    >>> a_list = [123, 'abc', 456]
    >>> a_list[2]
    456
    >>> a_list[2] = 789
    >>> a_list
    [123, 'abc', 789]
    >>>
    
  5. You may put a trailing comma when writing a tuple:

    >>> b_tuple = 2,3,
    >>> b_tuple
    (2, 3)
    >>>
    
  6. This comes in handy when writing a 1-tuple or singleton tuple which contains only one element.

    c = 2,
    

    If we had written it without a trailing comma, then it would represent the value of a number, not a tuple.

    Using parenteses doesn't help either, since they are used for grouping

    >>> d = (42)
    >>> d
    42
    >>> type(d)
    <type 'int'>
    
  7. The 0-tuple is just written with parentheses

    e_tuple = ()
    

Author: Breanndán Ó Nualláin <o@uva.nl>

Date: 2025-09-04 Thu 08:55