About Python Tuples

tags: #python/documentation/tuples

What is a Tuple?

A tuple is similar to a Python List. The difference is that we cannot change the elements of a tuple once it is assigned.

Use Case vs List

Tuples are often used to represent a collection of related values, and their immutability makes them suitable for situations where you want to ensure that the data remains unchanged. They are essentially unmodified versions of a list.

Tuples are more efficient in terms of memory use and performance. Ideally used when you want to create a temporary list of values that you will use and discard without modifying.

Creating a Tuple

A tuple is created by placing a sequence of comma separated list of values enclosed in parentheses (). Elements in a tuple can be homogenous or heterogenous:

this_tuple = (item1, item2, ...)

Creating a Tuple With 1 Element

When creating a tuple with 1 element, a trailing comma is required to indicate that it is a tuple:

var = (item1,)
Powered by Forestry.md