Tuple Definition

What is a Tuple?

In Python, a tuple is an ordered, immutable sequence of elements. Similar to a list, a tuple can contain elements of different data types. However, unlike lists which are mutable, tuples are immutable, meaning their content cannot be altered once created.

Structure of a Tuple

A tuple is enclosed with parentheses () and the elements inside the parentheses are separated by commas.

1my_tuple = ("Python", "Java", "C++", 42, 3.14)
2print(type(my_tuple))
3print(my_tuple)

In the code above, "Python", "Java", "C++", 42, and 3.14 are elements contained in the tuple my_tuple.

Characteristics of a Tuple

  1. Ordered: Tuples maintain an order of insertion, meaning the elements have a definitive sequence.

  2. Immutable: Once a tuple is created, you cannot modify its contents. This immutability provides certain advantages such as being able to use tuples as keys in dictionaries and as elements of sets.

  3. Allows Duplicate Values: A tuple can have elements with same values.

  4. Allows Multiple Data Types: A tuple can contain elements of different data types like integers, strings, lists, or even other tuples.

Here is an example showing the characteristics of a tuple:

1mixed_tuple = ("Python", "Java", "Python", 42, 3.14, ["apple", "banana"], ("a", "b", "c"))
2print(mixed_tuple)

In the mixed_tuple above, elements such as "Python", "Java", 42, 3.14, a list ["apple", "banana"] and another tuple ("a", "b", "c") are stored.

Note

A tuple with only one item is defined by including a trailing comma after the item. For example, single_item_tuple = ("Python",). Without the trailing comma, Python would not recognize it as a tuple.

Why Use a Tuple?

Tuples are generally used in cases where a statement or a user-defined function can safely assume that the collection of values (i.e. the tuple of values) will not change.