Tuple Methods
What You'll Learn: In this tutorial, you'll discover the built-in methods you can use on tuples in Python. Tuples are like lists, but they are immutable (unchangeable).
Tuple Methods
count()- Description: Returns the number of times a specified value occurs in a tuple.
Example Code:
pythonthistuple = ("apple", "banana", "cherry", "banana") print(thistuple.count("banana"))Output:
2- What's Happening Here?
thistuple.count("banana")counts how many times 'banana' appears inthistuple.
index()- Description: Searches the tuple for a specified value and returns the position of where it was found.
Example Code:
pythonthistuple = ("apple", "banana", "cherry") print(thistuple.index("cherry"))Output:
2- What's Happening Here?
thistuple.index("cherry")finds the position of 'cherry' inthistuple.
Try It Yourself: Fun Exercises
- Count Your Favorite Fruits:
- Create a tuple of your favorite fruits, with some duplicates.
- Use the
count()method to find out how many times a particular fruit appears.
- Find the Index:
- Write a tuple of different items.
- Use the
index()method to find the position of a specific item.
Summary:
In this Python tutorial, we learned about the two built-in methods for tuples: count() and index(). These methods help you analyze and work with tuple items efficiently. Keep experimenting and have fun with tuples in Python!