Similar to lists, tuples are a type of data structure in Python used to store a collection of items. However, unlike lists, tuples are immutable, meaning once they are created, their elements cannot be changed. This immutability makes tuples suitable for storing fixed collections of items. Here's an overview of tuples:
You can create a tuple by enclosing elements in parentheses `()`, separated by commas.
my_tuple = (1, 2, 3, 4, 5)
Like lists, you can access elements of a tuple using indexing. Python uses 0-based indexing.
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: 3
You can also use negative indexing and slicing, just like with lists.
As mentioned earlier, tuples are immutable. Once a tuple is created, you cannot change its elements.
my_tuple[0] = 10 # This will raise an error
To create a tuple with a single element, you need to include a trailing comma after the element. Otherwise, Python will treat it as a parenthesized expression.
single_tuple = (1,) # Single element tuple
not_a_tuple = (1) # Parenthesized expression
You can create a tuple without using parentheses. This is known as tuple packing.
my_tuple = 1, 2, 3
You can also unpack a tuple into individual variables.
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
Tuples have fewer methods compared to lists since they are immutable. Some common methods include:
Tuples are commonly used when you want to represent a collection of items that shouldn't be changed, such as coordinates, database records, or function return values.
coordinates = (3, 4) # (x, y) coordinates
person = ("John", 30) # (name, age) information
You can iterate over the elements of a tuple using a `for` loop, just like with lists.
for item in my_tuple:
print(item)
That's a basic overview of tuples in Python.