Python Access Tuple Items
Tuples are ordered collections of items. Accessing tuple items can be done in several ways including using positive and negative indexing, slicing, and looping.
Tuple क्रमबद्ध items का संग्रह होता है। Tuple के items को access करने के कई तरीके हैं जैसे positive और negative indexing, slicing, और looping।
Example 1: Access by Positive Index
t = ('apple', 'banana', 'cherry')
print(t[0])
Access the first item using positive index 0.
पहला item positive index 0 से access करें।
Output:
Example 2: Access by Negative Index
t = ('apple', 'banana', 'cherry')
print(t[-1])
Access the last item using negative index -1.
आखिरी item negative index -1 से access करें।
Output:
Example 3: Access a Range (Slicing)
t = (10, 20, 30, 40, 50)
print(t[1:4])
Access items from index 1 to 3 using slicing.
Index 1 से 3 तक के items slicing से access करें।
Output:
Example 4: Access from Start to a Specific Index
t = (10, 20, 30, 40, 50)
print(t[:3])
Access items from the start up to index 2.
शुरुआत से index 2 तक items access करें।
Output:
Example 5: Access from Specific Index to End
t = (10, 20, 30, 40, 50)
print(t[2:])
Access items from index 2 to the end.
Index 2 से अंत तक items access करें।
Output:
Example 6: Access Every Other Item (Step in Slice)
t = (0, 1, 2, 3, 4, 5)
print(t[::2])
Access every 2nd item using step 2 in slicing.
सभी alternate items step 2 से access करें।
Output:
Example 7: Access Last Few Items with Negative Slicing
t = (10, 20, 30, 40, 50)
print(t[-3:])
Access last 3 items using negative slicing.
negative slicing से आखिरी 3 items access करें।
Output:
Example 8: Loop through Tuple
t = ('a', 'b', 'c')
for item in t:
print(item)
Use a for loop to access all items.
for loop से सभी items access करें।
Output:
b
c
Example 9: Access Tuple with Index() Method
t = ('apple', 'banana', 'cherry')
print(t.index('banana'))
Find the index of an item using index() method.
index() method से item की position खोजें।
Output:
Example 10: Count Occurrences with count() Method
t = ('apple', 'banana', 'apple', 'cherry')
print(t.count('apple'))
Count how many times an item appears using count().
count() method से item की संख्या जानें।
Output: