Python Tuples
Python Tuples

Python Tuples

Tuples are ordered collections of heterogeneous data that are unchangeable. Learn how to use a tuple data structure in Python. Also, learn how to create, access, and modify a tuple.

Table of contents

What is a Tuple

Tuples are ordered collections of heterogeneous data that are unchangeable. Heterogeneous means tuple can store variables of all types.

Tuple has the following characteristics

  • Ordered: Tuples are part of sequence data types, which means they hold the order of the data insertion. It maintains the index value for each item.
  • Unchangeable: Tuples are unchangeable, which means that we cannot add or delete items to the tuple after creation.
  • Heterogeneous: Tuples are a sequence of data of different data types (like integer, float, list, string, etc;) and can be accessed through indexing and slicing.
  • Contains Duplicates: Tuples can contain duplicates, which means they can have items with the same value.
image

Creating a Tuple

Create a tuple with a single item

Tuple Packing and Unpacking in Python

Length of a Tuple

Iterating a Tuple

Accessing Items of a Tuple in Python

Finding an Item in a Tuple

Adding and changing items in a Tuple

Removing items from a tuple

Count the occurrence of an item in a tuple

Copying a tuple

Concatenating two Tuples

Nested tuples

Python Built-in functions with Tuples

min() and max()

all()

any()

When to use Tuple?

As tuples and lists are similar data structures, and they both allow sequential data storage, tuples are often referred to as immutable lists. So the tuples are used for the following requirements instead of lists.

  • There are no append() or extend() to add items and similarly no remove() or pop()methods to remove items. This ensures that the data is write-protected. As the tuples are Unchangeable, they can be used to represent read-only or fixed data that does not change.
  • As they are immutable, they can be used as a key for the dictionaries, while lists cannot be used for this purpose.
  • As they are immutable, the search operation is much faster than the lists. This is because the id of the items remains constant.
  • Tuples contain heterogeneous (all types) data that offers huge flexibility in data that contains combinations of data types like alphanumeric characters.