Introduction
Hello, fellow coders! Welcome back to our Python series on CipherTrick.com. In this tutorial, we are going to delve into another fundamental data structure in Python – Tuples. Tuples are like the more disciplined sibling of Lists. Let’s see why!
Part 1: What are Tuples?
Tuples, like lists, are used to store multiple items in a single variable. However, unlike lists, tuples are immutable, meaning you can’t change or modify them after they’re defined. This characteristic makes tuples a useful tool for data integrity. A tuple is created by enclosing the items (elements) in parentheses ()
.
fruits = ("apple", "banana", "cherry", "apple")
Part 2: Accessing Tuple Items
Items in a tuple are indexed just like lists, and you can access elements in a tuple by referring to their index number.
print(fruits[0]) # Outputs: apple
Part 3: Immutability of Tuples
As mentioned earlier, one of the key characteristics of tuples is that they are immutable. This means that you cannot change, add, or remove items after the tuple is created.
# The following code will raise an error
fruits[1] = "blueberry"
Part 4: When to use Tuples
You might be wondering, why use a tuple when it’s like a list but with fewer features? The power of tuples comes from their immutability. They are often used in Python to ensure data integrity, i.e., data that should not be changed once it’s written, such as days of the week or dates on a calendar.
Part 5: Tuple Methods
Since tuples are immutable, they don’t have methods like append() or remove() like lists do. But there are two methods you can use:
- count(): The count() method returns the number of times a specified value occurs in a tuple.pythonCopy code
count = fruits.count("apple")
- index(): The index() method finds the first occurrence of the specified value and returns its position.pythonCopy code
index = fruits.index("cherry")
Conclusion
Despite being less versatile than lists, tuples are a valuable data structure in Python due to their immutability. They are commonly used to hold related pieces of data, such as the coordinates of a point in two or three dimensions. In the upcoming tutorial, we will explore another fascinating Python data structure – Sets. Until then, keep practicing and happy coding!