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

  1. count()
    • Description: Returns the number of times a specified value occurs in a tuple.
    • Example Code:

      python
      thistuple = ("apple", "banana", "cherry", "banana")
      print(thistuple.count("banana"))
      
    • Output:

       
      2
      
    • What's Happening Here?
      • thistuple.count("banana") counts how many times 'banana' appears in thistuple.
  2. index()
    • Description: Searches the tuple for a specified value and returns the position of where it was found.
    • Example Code:

      python
      thistuple = ("apple", "banana", "cherry")
      print(thistuple.index("cherry"))
      
    • Output:

       
      2
      
    • What's Happening Here?
      • thistuple.index("cherry") finds the position of 'cherry' in thistuple.

Try It Yourself: Fun Exercises

  1. 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.
  2. 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!