Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Built-in Tuple Functions in Python
Python provides several built-in functions to work with tuples. These functions help you perform common operations like finding length, maximum/minimum values, and converting sequences to tuples.
len() Function
The len() function returns the total number of elements in a tuple ?
numbers = (1, 2, 3, 4, 5)
fruits = ('apple', 'banana', 'orange')
empty_tuple = ()
print("Length of numbers:", len(numbers))
print("Length of fruits:", len(fruits))
print("Length of empty tuple:", len(empty_tuple))
Length of numbers: 5 Length of fruits: 3 Length of empty tuple: 0
max() Function
The max() function returns the element with the highest value from the tuple ?
numbers = (45, 12, 89, 23, 67)
letters = ('z', 'a', 'm', 'k')
print("Maximum number:", max(numbers))
print("Maximum letter:", max(letters))
Maximum number: 89 Maximum letter: z
min() Function
The min() function returns the element with the lowest value from the tuple ?
numbers = (45, 12, 89, 23, 67)
letters = ('z', 'a', 'm', 'k')
print("Minimum number:", min(numbers))
print("Minimum letter:", min(letters))
Minimum number: 12 Minimum letter: a
tuple() Function
The tuple() function converts any iterable (list, string, set) into a tuple ?
# Convert list to tuple
numbers_list = [1, 2, 3, 4, 5]
numbers_tuple = tuple(numbers_list)
# Convert string to tuple
text = "hello"
char_tuple = tuple(text)
# Convert set to tuple
numbers_set = {10, 20, 30}
set_tuple = tuple(numbers_set)
print("From list:", numbers_tuple)
print("From string:", char_tuple)
print("From set:", set_tuple)
From list: (1, 2, 3, 4, 5)
From string: ('h', 'e', 'l', 'l', 'o')
From set: (10, 20, 30)
Summary
| Function | Purpose | Example |
|---|---|---|
len(tuple) |
Returns number of elements |
len((1, 2, 3)) ? 3 |
max(tuple) |
Returns largest element |
max((1, 5, 3)) ? 5 |
min(tuple) |
Returns smallest element |
min((1, 5, 3)) ? 1 |
tuple(seq) |
Converts sequence to tuple |
tuple([1, 2]) ? (1, 2) |
Conclusion
These built-in functions make tuple manipulation easy and efficient. Use len() for size, max()/min() for extremes, and tuple() for conversions from other sequences.
Advertisements
