Python tuple Function & Methods
In Python, tuples are immutable, meaning their
elements cannot be modified once the tuple is created. Consequently, there are
only a few built-in methods specific to tuples, as they are more limited
compared to mutable types like lists. However, there are some functions and
operations that can be performed on tuples. Here are some key functions and
methods related to tuples in Python:
Built-in
Functions:
len():
Returns the length (number of elements) of a tuple.
my_tuple = (1, 2, 3, 'a', 'b', 'c')
length = len(my_tuple)
print(length) # Output: 6
max()
and min():
Returns the maximum or minimum element in the
tuple.
numbers = (10, 5, 8, 20)
max_value = max(numbers)
min_value = min(numbers)
print(max_value,
min_value)
#
Output: 20 5
sum():
Returns the sum of all elements in a tuple (if all
elements are numeric).
numbers = (1, 2, 3, 4, 5)
total = sum(numbers)
print(total)
#
Output: 15
Tuple
Methods:
count():
Returns the number of occurrences of a specified
value in the tuple.
my_tuple = (1, 2, 3, 'a', 'b', 'a')
count_a = my_tuple.count('a')
print(count_a)
# Output: 2
index():
Returns the index of the first occurrence of a
specified value.
my_tuple = (1, 2, 3, 'a', 'b', 'a')
index_a = my_tuple.index('a')
print(index_a)
# Output: 3
Functions
That Work with Tuples:
sorted():
Returns a new sorted list from the elements of a
tuple.
my_tuple = (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)
sorted_list = sorted(my_tuple)
print(sorted_list)
# Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
tuple():
Converts a sequence (e.g., a list or string) into a
tuple.
my_list = [1, 2, 3, 4]
converted_tuple = tuple(my_list)
print(converted_tuple)
# Output: (1, 2, 3, 4)
These functions and methods provide basic
functionality for working with tuples in Python. Remember that, due to their
immutability, many list methods, like append() or remove(),
are not applicable to tuples. If you need to modify a collection, consider
using a list instead.
Comments
Post a Comment