← Back to Python Course | Chapter 6: Data Structures | Lesson 3 of 12

Python Tuples

Tuple एक ऐसी list की तरह है जो एक box में seal कर दी गई हो: आप अंदर जो है उसे पढ़ सकते हैं पर बदल नहीं सकते। यह उन चीज़ों के लिए अच्छा है जिन्हें fixed रहना चाहिए, जैसे किसी जगह के coordinates।
Syntax
python
tuple_name = (item1, item2, item3)
tuple_name[index]

Tuple क्या है?

Tuple list जैसा ही एक ordered collection है, पर एक बार बन जाने के बाद उसके elements को reassign, add या remove नहीं किया जा सकता — यह immutability tuples को dictionary keys के रूप में इस्तेमाल करने लायक बनाती है और readers को बताती है कि यह data बदलना नहीं चाहिए, जैसे coordinates (x, y)।

उदाहरण: What is a Tuple?

python
point = (3, 4)
print(point)

Tuple Items को Access करना

Tuples बिल्कुल वही square-bracket indexing और slicing support करते हैं जो lists करती हैं, इसलिए my_tuple[0] और my_tuple[1:3] बिल्कुल वैसे ही काम करते हैं — असली फ़र्क बस इतना है कि बाद में उनके through assign नहीं किया जा सकता।

उदाहरण: Accessing Tuple Items

python
point = (3, 4, 5)
print(point[0])  # index like a list
print(point[1:3])  # slice like a list, returns a tuple

Tuple Unpacking

Unpacking से आप x, y = point लिखकर किसी tuple की values को एक ही line में named variables में निकाल सकते हैं, यही वजह है कि कई values लौटाने वाले functions (जैसे divmod()) उन्हें tuple के रूप में लौटाते हैं जिन्हें आप तुरंत destructure कर सकते हैं।

उदाहरण: Tuple Unpacking

python
point = (3, 4)
x, y = point  # unpacks the tuple's values into x and y
print(x, y)

Tuple Operations

आप किसी tuple को in place modify नहीं कर सकते, पर + दो tuples को जोड़कर एक बिल्कुल नया tuple बना देता है और * किसी tuple के elements को repeat करता है, दोनों ही originals को छुए बिना नए tuple objects बनाते हैं।

उदाहरण: Tuple Operations

python
a = (1, 2)
b = (3, 4)
print(a + b)  # concatenates into a new tuple
print(a * 2)  # repeats a's elements into a new tuple

Tuple Methods

चूँकि tuples न बढ़ सकते हैं न सिकुड़ सकते हैं, उन्हें सिर्फ count(value) (कोई value कितनी बार आती है) और index(value) (उसकी पहली position) की ज़रूरत होती है — support करने के लिए कोई append या remove नहीं है।

उदाहरण: Tuple Methods

python
t = (1, 2, 2, 3)
print(t.count(2))  # how many times 2 appears
print(t.index(3))  # position of the first 3
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.