tuples in python

  • Recall that a list is a collection of ordered objects. The main characteristic of the tuple is that once created, it cannot be modified.
  • That is why they are referred to as “immutable lists.” Python objects are sometimes divided into mutable and immutable.
  • As the name implies, immutable objects cannot be modified after they are created.
  • You can easily tell a tuple from a list because the tuple’s elements are enclosed between parentheses instead of square brackets.
  • Tuples are sequences, just like lists. The only difference is that tuples can’t be changed.
  • The tuple syntax is simple—if you separate some values with commas, you automatically have a tuple:
  • >>> 1, 2, 3
    (1, 2, 3)

The tuple Function

The tuple function works in pretty much the same way as list: it takes one sequence argument and converts it to a tuple.6 If the argument is already a tuple, it is returned unchanged:

    >>> tuple([1, 2, 3])
    (1, 2, 3)
    >>> tuple('abc')
    ('a', 'b', 'c')
    >>> tuple((1, 2, 3))
    (1, 2, 3)

Basic Tuple Operations

As you may have gathered, tuples aren’t very complicated—and there isn’t really much you can do with them except create them and access their elements, and you do this the same as with other sequences:

    >>> x = 1, 2, 3
    >>> x[1]
    >>> x[0:2]
    (1, 2)