Python Tuple Methods and Useful Functions
Tuples are immutable in Python and have only two built-in methods: count()
and index()
. But you can also use many useful built-in functions with tuples such as len()
, max()
, min()
, sum()
, sorted()
, and reversed()
.
Python में tuples immutable होते हैं और इनके केवल दो built-in methods होते हैं: count()
और index()
. लेकिन आप tuples के साथ कई उपयोगी built-in functions भी इस्तेमाल कर सकते हैं जैसे len()
, max()
, min()
, sum()
, sorted()
, और reversed()
।
Why and when to use tuple methods/functions?
- To count occurrences of an element.
- To find the position of an element.
- To get length, max, min, sum of tuple elements.
- To get sorted or reversed versions of tuples.
- For efficient, immutable data handling.
- किसी element की संख्या गिनने के लिए।
- किसी element का स्थान जानने के लिए।
- Tuple के elements की length, max, min, sum निकालने के लिए।
- Tuple को sorted या reversed करने के लिए।
- Immutable data को efficient तरीके से handle करने के लिए।
1. count(value) Method
t = (1, 2, 2, 3, 2)
print(t.count(2))
Counts how many times 2 appears in the tuple.
Tuple में 2 कितनी बार आया है, गिनता है।
Output:
2. index(value[, start[, end]]) Method
t = ('a', 'b', 'c', 'b')
print(t.index('b'))
Finds the first index of 'b' in the tuple.
'b' का पहला index बताता है।
Output:
3. len(tuple)
t = (1, 2, 3, 4)
print(len(t))
Returns the number of elements in the tuple.
Tuple में elements की संख्या बताता है।
Output:
4. max(tuple)
t = (10, 20, 30, 40)
print(max(t))
Returns the maximum element in the tuple.
Tuple में सबसे बड़ा element बताता है।
Output:
5. min(tuple)
t = (10, 20, 30, 40)
print(min(t))
Returns the minimum element in the tuple.
Tuple में सबसे छोटा element बताता है।
Output:
6. sum(tuple)
t = (1, 2, 3, 4)
print(sum(t))
Returns the sum of all elements in the tuple.
Tuple के सभी elements का जोड़ बताता है।
Output:
7. sorted(tuple)
t = (3, 1, 4, 2)
print(sorted(t))
Returns a sorted list from the tuple elements.
Tuple के elements को sorted list के रूप में देता है।
Output:
8. reversed(tuple)
t = (1, 2, 3, 4)
print(tuple(reversed(t)))
Returns a reversed tuple using reversed() and tuple().
reversed() और tuple() से उल्टा tuple बनाता है।
Output:
9. any(tuple)
t = (False, 0, True)
print(any(t))
Returns True if any element is True.
अगर कोई भी element True हो तो True देता है।
Output:
10. all(tuple)
t = (True, 1, 'non-empty')
print(all(t))
Returns True if all elements are True.
अगर सभी elements True हों तो True देता है।
Output: