Tuples are immutable sequences of elements, enclosed in parentheses (). They are similar to lists in Python, but unlike lists, tuples cannot be modified after they are created.
Tuples can be created using the tuple() function or by simply enclosing comma-separated values in parentheses.
# Creating a tuple using the tuple() function
my_tuple1 = tuple()
# Creating a tuple with values
my_tuple2 = (1, 2, 3, 4, 5)
# Creating a tuple with mixed data types
my_tuple3 = ('apple', 10, 3.14, True)
Tuple elements can be accessed using indexing, similar to lists. Indexing starts from 0.
# Accessing tuple elements
print(my_tuple2[0]) # Output: 1
print(my_tuple2[2]) # Output: 3
Tuples can be sliced to extract a portion of the tuple. Slicing follows the syntax [start:end:step], where start is the starting index, end is the ending index (exclusive), and step is the step size.
# Slicing a tuple
print(my_tuple2[1:4]) # Output: (2, 3, 4)
print(my_tuple2[0:5:2]) # Output: (1, 3, 5)
Tuples are immutable, which means their elements cannot be modified after they are created. However, you can create a new tuple with modified elements.
# Modifying tuple elements
my_tuple4 = my_tuple2 + (6, 7, 8)
print(my_tuple4) # Output: (1, 2, 3, 4, 5, 6, 7, 8)
You can unpack a tuple into multiple variables. The number of variables must match the number of elements in the tuple.
# Tuple unpacking
a, b, c = my_tuple2
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3