Python Tuple Tutorial
A tuple in Python is an ordered, immutable collection of items. Once a tuple is created, its elements cannot be changed (no add, remove or update). Tuples are similar to lists but offer performance benefits and ensure data integrity.
Python में tuple एक ordered और immutable collection होता है। एक बार tuple बन जाने के बाद आप इसके elements को बदल (add, remove या update) नहीं सकते। Tuple list की तरह होते हैं लेकिन ये बेहतर performance देते हैं और data को सुरक्षित रखते हैं।
Why Use Tuples?
- To protect data from accidental modification.
- Tuples are faster than lists.
- Can be used as keys in dictionaries (lists cannot).
- Used to represent fixed collections of items.
- डेटा को गलती से बदलने से बचाने के लिए।
- Tuples lists से तेज होते हैं।
- Dictionaries में key के रूप में इस्तेमाल किए जा सकते हैं (lists नहीं)।
- Fixed items के समूह को दर्शाने के लिए।
When to Use Tuples?
- When the data should not change throughout the program.
- When you want to ensure data integrity.
- When you need a collection of heterogenous data with fixed size.
- When you want to use the collection as a dictionary key.
- जब डेटा पूरे प्रोग्राम में स्थिर रहे।
- जब डेटा की सुरक्षा जरूरी हो।
- जब fixed size और अलग-अलग प्रकार के डेटा की जरूरत हो।
- जब collection को dictionary key के रूप में उपयोग करना हो।
Example 1: Creating a Tuple
t = (10, 20, 30)
print(t)
Create a tuple with 3 numbers and print it.
3 नंबर वाले tuple बनाएं और प्रिंट करें।
Output:
Example 2: Access Tuple Items
t = ('apple', 'banana', 'cherry')
print(t[1])
Access tuple element by index (index starts at 0).
index 1 से tuple का element प्राप्त करें (index 0 से शुरू होता है)।
Output:
Example 3: Tuple Immutability
t = (1, 2, 3)
# t[0] = 10 # This will cause error
print(t)
Trying to change tuple item causes error (commented here).
tuple item को बदलने की कोशिश error देगा (यहाँ comment किया गया है)।
Output:
Example 4: Single Item Tuple
t = (5,)
print(type(t))
Tuple with single item needs a trailing comma.
एक item वाले tuple के लिए trailing comma जरूरी है।
Output:
Example 5: Tuple Without Parentheses
t = 1, 2, 3
print(t)
Parentheses are optional when defining tuples.
tuple बनाने में parentheses optional हैं।
Output:
Example 6: Tuple Packing and Unpacking
t = (10, 20, 30)
a, b, c = t
print(a, b, c)
Assign tuple values to variables using unpacking.
tuple के values को variables में unpack करें।
Output:
Example 7: Using Tuple as Dictionary Key
d = { (1,2): 'a', (3,4): 'b' }
print(d[(1,2)])
Tuples can be used as dictionary keys because they are immutable.
Tuples immutable होने की वजह से dictionary key बन सकते हैं।
Output: