Page Contents
Executive Page Summary
Tuples are a type of data structure in Python that allow you to store values together. They are similar to lists, but there are some key differences that make them useful in certain situations.
Tuples are ordered, immutable, and indexed collections of objects. They are sequences, just like lists, but with the key difference of being immutable. This means that once a tuple is created, its elements cannot be added, removed or changed. Tuples are created using parentheses or the tuple()
function, and elements are separated by commas.
# Creating a Tuple
my_tuple = (1, 2, 3)
Tuple elements can be accessed using indexing, just like with lists. For example:
my_tuple = (1, 2, 3)
print(my_tuple[0]) # Output: 1
Tuples also support slicing, which allows you to access multiple elements at once. Slicing works the same way it does with lists:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4]) # Output: (2, 3, 4)
One key difference between tuples and lists is that tuples are immutable, meaning they cannot be changed once they are created. This means you cannot add, remove, or modify elements of a tuple. Any attempt to change a tuple will result in a TypeError.
my_tuple = (1, 2, 3)
my_tuple[0] = 4 # Raises TypeError: 'tuple' object does not support item assignment
However, you can create a new tuple by concatenating two or more tuples using the +
operator:
my_tuple = (1, 2, 3)
new_tuple = my_tuple + (4, 5)
print(new_tuple) # Output: (1, 2, 3, 4, 5)