Python Tuple
Python Tuple Methods with Examples
In Python, a tuple is an ordered, immutable collection of elements. Tuples are very similar to lists, but unlike lists, tuples cannot be changed after they are created. Below are the methods available for tuples in Python:
- count(x): Returns the number of occurrences of item 'x' in the tuple.
# Example:
my_tuple = (1, 2, 2, 3)
count_of_2 = my_tuple.count(2)
print(count_of_2) # Output: 2
- index(x[, start[, end]]): Returns the index of the first occurrence of item 'x' in the tuple. You can specify the start and end indices for searching.
# Example:
my_tuple = (1, 2, 3, 2)
index_of_2 = my_tuple.index(2)
print(index_of_2) # Output: 1
Python Tuple Overview
A Python tuple is an ordered collection of items, similar to a list. However, unlike lists, tuples are **immutable**, meaning once created, their elements cannot be changed. Tuples are often used for fixed collections of data, such as coordinates or pairs of related values.
Creating a Tuple
# Example:
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
Accessing Tuple Elements
# Example:
my_tuple = (1, 2, 3)
print(my_tuple[0]) # Output: 1
Nested Tuples
# Example:
nested_tuple = (1, (2, 3), 4)
print(nested_tuple[1]) # Output: (2, 3)
Why Use Tuples?
Tuples are typically used when you want to ensure that the collection of items cannot be modified. They are faster than lists when it comes to iteration and are often used to store data that should remain constant, such as geographical coordinates or RGB values.