Introduction to Tuples in Python
Tuples are a built-in data type in Python that is used to store a collection of values. Like lists, tuples can contain any type of data, including numbers, strings, and other objects. However, unlike lists, tuples are immutable, meaning that their values cannot be changed once they are created. Tuples are often used to group related values together, or to return multiple values from a function.
Creating a Tuple
A tuple can be created by enclosing a sequence of values in parentheses. For example:
my_tuple = (1, 2, 3)
This creates a tuple with the values 1, 2, and 3. Alternatively, a tuple can also be created without using parentheses, by separating the values with commas:
my_tuple = 1, 2, 3
This also creates a tuple with the values 1, 2, and 3.
Accessing Tuple Values
Tuple values can be accessed using indexing, just like with lists. The first value in a tuple has an index of 0, the second value has an index of 1, and so on. For example:
my_tuple = (1, 2, 3) print(my_tuple[0]) # Output: 1