Tuples

A tuple is a data structure used to store an ordered and immutable collection of objects, unlike dictionaries which are unordered and mutable. They are similar to lists, except that tuples cannot be changed after creation.

Tuples also support built-in sequence functions such as len(), min(), max().

Syntax

# With built-in function
tuple(value1, value2, ... valueN)

# With parentheses (multi-item)
tuple = (value1, value2, ... valueN)

# With parentheses (single item with a trailing comma)
tuple = (singleValue, )

There are multiple ways to create tuples in Python:

  • The first way is with the built-in tuple() function that accepts an iterable value such as a list.
  • Tuples can also be created with just parentheses.

Note: If the tuple is made with just parentheses and has only one element, it must contain a trailing comma. Otherwise, Python will interpret the surrounding parentheses as an expression instead of a tuple:

streaming_days = (3)
print(f"Value is {streaming_days}. Type is {type(streaming_days)}")
# Output: Value is 3. Type is <class 'int'>

Codebyte Example

The following example shows how tuples are like lists in that they are ordered and their elements can be accessed by index. However, since tuples are immutable, we cannot modify, delete, or add new elements. Attempting to re-assign an element will throw a TypeError:

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Python on Codecademy