Tuples

A tuple is an immutable list. Immutable means that it cannot be modified. A tuple is just a comma-separated sequence of objects (a list without brackets). To increase readability, one often encloses a tuple in a pair of parentheses:

my_tuple = 1, 2, 3     # our first tuple
my_tuple = (1, 2, 3)   # the same
my_tuple = 1, 2, 3,    # again the same
len(my_tuple) # 3, same as for lists
my_tuple[0] = 'a'   # error! tuples are immutable

The comma indicates that the object is a tuple:

singleton = 1,   # note the comma
len(singleton)   # 1

Tuples are useful when a group of values goes together; for example, they are used to return multiple values from functions (refer to section Returns Values in Chapter 7, Functions. One may assign several variables at once by unpacking ...

Get Scientific Computing with Python 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.