tuple

The built-in tuple data type provides an immutable sequence of values, which can store any data type. Tuples are useful for storing heterogeneous data, such as records in a database or fixed collections of items:

Python
>>> coordinates = (10.5, 20.3)
>>> person = ("Alice", 30, "Engineer")

tuple Literals

In Python, you can use different literal to create tuples:

Literal Type Syntax Example Description
Empty tuple () An empty tuple, denoted simply by an empty pair of parentheses
Single-item tuple (item,) or item, A tuple with a single element requires a trailing comma to differentiate from parentheses
Multiple-item tuple (1, 2, 3) or 1, 2, 3 A standard tuple with multiple elements separated by commas

tuple Constructor

Python Syntax
tuple(iterable)

Arguments

Argument Description
iterable An iterable object whose elements are to be included in the tuple.

Return Value

  • Returns a Python tuple object

tuple Examples

You can create an empty tuple using a pair of parentheses:

Python
>>> empty_tuple = ()
>>> empty_tuple
()

You can create tuples using literals:

Python
>>> numbers = (1, 2, 3)
>>> numbers
(1, 2, 3)

>>> record = "Jane Doe", 25, "Canada"
>>> record
('Jane Doe', 25, 'Canada')

Create a tuple from a list using the tuple() constructor:

Python
>>> tuple([1, 2, 3])
(1, 2, 3)

Accessing values in a tuple throuhg indexing:

Python
>>> numbers[0]
1
>>> record[2]
'Canada'

tuple Methods

Method Description
.count() Returns the number of times a specified value appears in the tuple.
.index() Returns the index of the first occurrence of a specified value.

tuple Common Use Cases

The most common use cases for the tuple include:

  • Storing fixed collections of related data
  • Returning multiple values from a function
  • Grouping data that shouldn’t change over time

tuple Real-World Example

Imagine you’re working on a program that processes RGB color values. Tuples are perfect for this task because they hold a fixed number of elements:

Python
>>> rgb_red = (255, 0, 0)
>>> rgb_green = (0, 255, 0)
>>> rgb_blue = (0, 0, 255)

In this example, each tuple holds an RGB color. Tuples’ immutability ensures that these colors remain constant and unchanged throughout your program.

Tutorial

Python's tuple Data Type: A Deep Dive With Examples

In Python, a tuple is a built-in data type that allows you to create immutable sequences of values. The values or items in a tuple can be of any type. This makes tuples pretty useful in those situations where you need to store heterogeneous data, like that in a database record, for example.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 6, 2024 • Reviewed by Dan Bader