What is Tuple in Python with examples

Tuples are similar to lists in Python, but they are immutable, meaning once a tuple is created, its elements cannot be changed. Tuples are also ordered, meaning the elements inside a tuple have a defined order.

Tuples are written inside parentheses, like this:

(12, 13, 14)

Here are some examples of tuples in Python:

# Tuple of numbers
numbers = (1, 2, 3, 4, 5)

# Tuple of strings
names = ("John", "Jane", "Jim")

# Tuple of mixed data types
mixed = (1, "apple", 3.14, True)

# Tuple of tuples
nested = ((1, 2), (3, 4), (5, 6))

# Empty tuple
empty = ()

Tuples are useful for situations where you want to group multiple items together but don’t want to allow any changes to those items later.

Different Methods in Tuple with respective Examples

Here are some of the methods available for tuples in Python:

  1. count(): returns the number of times a specified value appears in the tuple.

Example:

numbers = (1, 2, 3, 4, 5, 3)
count_of_three = numbers.count(3)
print(count_of_three) # Output: 2
  1. index(): returns the index of the first occurrence of the specified value in the tuple.

Example:

numbers = (1, 2, 3, 4, 5, 3)
index_of_three = numbers.index(3)
print(index_of_three) # Output: 2
  1. len(): returns the length of the tuple.

Example:

numbers = (1, 2, 3, 4, 5, 3)
length_of_numbers = len(numbers)
print(length_of_numbers) # Output: 6
  1. max(): returns the maximum value in the tuple.

Example:

numbers = (1, 2, 3, 4, 5)
maximum_number = max(numbers)
print(maximum_number) # Output: 5
  1. min(): returns the minimum value in the tuple.

Example:

numbers = (1, 2, 3, 4, 5)
minimum_number = min(numbers)
print(minimum_number) # Output: 1
  1. sorted(): returns a sorted list from the elements in the tuple.

Example:

numbers = (5, 3, 4, 1, 2)
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 4, 5]

Note that these methods work only on tuples containing elements of the same data type.

Leave a Comment