What is a Tuple?
In Python, a tuple is an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, meaning that their elements cannot be modified after they are created. Tuples are denoted by parentheses ()
and the elements are separated by commas.
Tuples are often used to store related data that should be treated as a single unit, such as the coordinates of a point in a 2D or 3D space, or the name and age of a person.
Here's an example of a tuple:
point = (2, 3)
person = ("John Doe", 35)
In the first example, point
is a tuple that represents the coordinates of a point in a 2D space. In the second example, person
is a tuple that represents the name and age of a person.
Tuples can contain elements of different data types, including numbers, strings, and even other tuples or lists. Here's an example:
mixed_tuple = (1, "hello", 3.14, (True, False))
In this example, mixed_tuple
is a tuple that contains an integer, a string, a float, and another tuple.
One of the key advantages of using tuples over lists is that they are immutable, which means that their elements cannot be modified after they are created. This can be useful in situations where you want to ensure that the data remains consistent and unchanged.
graph TD
A[Tuple] --> B[Ordered Collection]
A --> C[Immutable]
A --> D[Store Related Data]
B --> E[Similar to List]
C --> F[Elements Cannot be Modified]
D --> G[Coordinates, Name-Age]
Overall, tuples are a versatile data structure in Python that can be used to store and manipulate data in a variety of contexts.