Python Tuples


A tuple is a fixed-length, immutable sequence of Python objects which, once assigned cannot be changed. You can create a tuple simply by writing a comma-separated sequence of values wrapped in parentheses. In many contexts, the parentheses can actually be omitted.

Tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

Below is an example of creating a list of tuples. Tuples use a pair of round brackets ( ). Lists use square brackets. Dictionaries use curly brackets { }.

# a list of tuples, having name, age and position
team = [
    ('Marta', 20, 'center'),
    ('Ana', 22, 'point guard'),
    ('Gabi', 22, 'shooting guard'),
    ('Luz', 21, 'power forward'),
    ('Lorenza', 19, 'small forward'),
    ('Suzie', 20, 'point guard')
]

You can instantiate a tuple in two ways: parentheses and the tuple() function.

More Information

Here is an article called Tuples and Sequences.

Leave a Reply