Welcome back! In our journey through Python's data structures, we've explored lists, which are wonderfully flexible. Now, let's introduce another fundamental collection type: tuples. Tuples are similar to lists in that they can store an ordered sequence of items, but they come with a crucial difference: they are immutable. This means once a tuple is created, its contents cannot be changed, added to, or removed from. Think of them as a fixed snapshot of data.
Why would you want an immutable collection? Immutability offers several advantages. Firstly, it can make your code more predictable, as you're guaranteed that the data in a tuple won't accidentally be altered elsewhere in your program. Secondly, immutable objects are generally more memory-efficient and can be used as keys in dictionaries, which we'll cover later, because their hash values remain constant.
Creating a tuple is very straightforward. You enclose a sequence of items within parentheses () and separate them with commas. If you have only one item in a tuple, you must include a trailing comma to distinguish it from a simple value. Let's look at some examples.
my_tuple = (1, 2, 3, 'apple', 'banana')
empty_tuple = ()
single_item_tuple = (42,)
no_parentheses_tuple = 10, 20, 30Accessing elements within a tuple works exactly like accessing elements in a list, using square brackets [] and zero-based indexing. You can retrieve individual items or slices of the tuple.
fruits = ('apple', 'banana', 'cherry')
first_fruit = fruits[0] # 'apple'
second_fruit = fruits[1] # 'banana'
last_fruit = fruits[-1] # 'cherry'
subset_fruits = fruits[0:2] # ('apple', 'banana')Now, let's demonstrate the immutability of tuples. If you try to modify an element or reassign it, Python will raise a TypeError. This is a key distinction from lists.
# This will cause an error!
# fruits[0] = 'orange'
# This will also cause an error!
# fruits.append('grape')