Tuples

In Python, tuples are immutable objects, which means they cannot be modified once created. However, there are several built-in functions and methods that you can use with tuples. Here are some commonly used functions and methods for working with tuples in Python:

  1. len(): Returns the number of elements in a tuple.
    • fruits = ("apple", "banana", "cherry")
    • length = len(fruits)
    • print(length) # Output: 3
  2. index(): Returns the index of the first occurrence of a specified element in the tuple.
    • fruits = ("apple", "banana", "cherry", "banana")
    • index = fruits.index("banana")
    • print(index) # Output: 1
  3. count(): Returns the number of occurrences of a specified element in the tuple.
    • fruits = ("apple", "banana", "cherry", "banana")
    • count = fruits.count("banana")
    • print(count) # Output: 2
  4. sorted(): Returns a new sorted list of elements from the tuple (not modifying the original tuple).
    • numbers = (3, 1, 4, 2, 5)
    • sorted_numbers = sorted(numbers)
    • print(sorted_numbers) # Output: [1, 2, 3, 4, 5]
  5. tuple(): Converts an iterable object (such as a list or string) into a tuple.
    • my_list = [1, 2, 3]
    • my_tuple = tuple(my_list)
    • print(my_tuple) # Output: (1, 2, 3)

These functions and methods can help you perform various operations on tuples in Python. Remember that since tuples are immutable, you cannot modify them directly. However, you can utilize these functions and methods to manipulate and work with tuples effectively.

Leave a comment