Tuple

Revision as of 16:18, 19 April 2011 by Smitschu (talk | contribs) (Created page with ''''Tuples''' in Python are used to store multiple items in a single ordered set. However, unlike lists, tuples are ''immutable'' - they can't be changed after they're cr…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Tuples in Python are used to store multiple items in a single ordered set. However, unlike lists, tuples are immutable - they can't be changed after they're created. This is desirable in some cases. For example, only immutable objects like tuples and strings can be used as keys in dictionaries.

Basics

To create a tuple, you place one or more comma separated elements in parentheses. For example, the following tuple has three elements:

myTuple = (1+3, 2.7, 'Thursday')

To create a tuple with only one element you need a trailing comma, to signify to Python you want a tuple rather than just an expression in parentheses:

x = (7,) # assigns to x a tuple with only one element, the number 7
x = (7)  # assigns to x the number 7, not a tuple

To access the i'th element of a tuple, use the name of the tuple followed by the index in square brackets. Note that like other sequences in Python, tuples are zero-indexed.

Useful Functions

All the generic sequence functions and operations also apply to tuples.

See Also

Python 3.2 Sequence Documentation