tuple | Python’s Built-in Data Types – Real Python

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

tuple Literals

In Python, you can use different literals 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 regular parentheses
Multiple-item tuple (1, 2, 3) or 1, 2, 3 A standard tuple with multiple elements separated by commas

tuple Constructor

Arguments

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

Return Value

  • Returns a Python tuple object

tuple Examples

Creating an empty tuple using a pair of parentheses:

Creating tuples using literals:

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

Accessing values in a tuple through indexing:

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 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:

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: