The Story That Explains Tuples ✉️Tuples समझाने वाली कहानी ✉️一个解释元组的故事 ✉️
A Python tuple is that sealed envelope. It groups related values in a fixed order, and once it is made, its contents cannot change. You can read any slot, slice it and pass it to functions, but any attempt to change it raises an error. This makes tuples safer, a little smaller, and usable as dictionary keys — things lists cannot offer.
Use tuples for records that should not change: a GPS point (28.6139, 77.2090), an RGB colour (255, 128, 0), a database row, or several values returned from one function.
Python का tuple वही मुहरबंद लिफ़ाफ़ा है। यह जुड़े हुए मानों को तय क्रम में रखता है, और बनने के बाद इसकी सामग्री नहीं बदल सकती। आप कोई भी slot पढ़ सकते हैं, slice कर सकते हैं, functions को दे सकते हैं, पर बदलने की हर कोशिश error देती है। इससे tuples ज़्यादा सुरक्षित, थोड़े छोटे, और dictionary keys के लायक़ बनते हैं — जो lists नहीं दे सकतीं।
न बदलने वाले records के लिए tuples लगाएँ: GPS point (28.6139, 77.2090), RGB रंग (255, 128, 0), database की एक row, या किसी function से लौटे कई मान।
Python 的元组就是那个封好的信封。它按固定顺序把相关的值放在一起,一旦创建,内容就不能改变。你可以读取任何槽位、切片、把它传给函数,但任何修改的尝试都会报错。这让元组更安全、略更小,并且可以作为字典的键 —— 这些都是列表做不到的。
把元组用于不应改变的记录:GPS 坐标 (28.6139, 77.2090)、RGB 颜色 (255, 128, 0)、数据库中的一行,或一个函数返回的多个值。
A tuple (tuple) is Python's built-in ordered, immutable sequence. Ordered means position matters. Immutable means it cannot be changed after it is made. Think of tuples as the stricter sibling of lists: fewer features, more guarantees.
Tuple (tuple) Python का built-in क्रमबद्ध, न बदलने वाला sequence है। क्रमबद्ध यानी जगह मायने रखती है। Immutable यानी बनने के बाद बदला नहीं जा सकता। Tuples को lists का अनुशासित भाई समझें: कम features, ज़्यादा गारंटी।
元组(tuple)是 Python 内置的有序、不可变序列。有序是指位置很重要;不可变是指创建后不能修改。可以把元组看作列表更严格的兄弟:功能更少,保证更多。
Look for the live boxes: the Comma Detector (Section 02), the Mutation Lab (03) and the Unpacking Lab (09). Every result they show was produced by real Python.
Live boxes देखें: Comma Detector (Section 02), Mutation Lab (03) और Unpacking Lab (09)। इनका हर नतीजा असली Python से निकाला गया है।
留意这些互动框:逗号探测器(第 02 节)、修改实验室(03)和拆包实验室(09)。它们显示的每个结果都由真实的 Python 生成。
Creating Tuples — Five Ways (and One Big Gotcha) ✍️Tuples बनाना — पाँच तरीक़े (और एक बड़ा जाल) ✍️创建元组 —— 五种方式(和一个大陷阱)✍️
# 1. Literal with parentheses (most common)
empty = ()
point = (28.6139, 77.2090) # New Delhi (lat, lon)
rgb = (255, 128, 0)
mixed = ("Asha", 30, 5.4, True)
nested = ((1, 2), (3, 4), (5, 6))
# 2. Without parentheses — the COMMAS make the tuple
coords = 3, 4
person = "Ravi", 25
# 3. One item: the famous trap
not_a_tuple = (5) # just the int 5
real_tuple = (5,) # the trailing comma makes it a tuple
also_tuple = 5,
# 4. The tuple() constructor
from_list = tuple([1, 2, 3])
from_str = tuple("hello")
from_range = tuple(range(5))
# 5. A generator expression passed to tuple()
squares = tuple(x ** 2 for x in range(1, 6))
gen = (x ** 2 for x in range(1, 6)) # NOT a tuple — a generator!
print(empty, point, rgb, mixed, nested)
print(coords, person)
print(type(not_a_tuple).__name__, type(real_tuple).__name__, also_tuple)
print(from_list, from_str, from_range)
print(squares, type(gen).__name__)
(5) is NOT a tuple. It is just the integer 5 inside grouping parentheses, as in maths. To make a one-item tuple you need a trailing comma: (5,). Commas make tuples; parentheses only help reading. Even 5, with no parentheses is a tuple. Also note the last line: (x ** 2 for x in ...) is a generator, not a tuple.
(5) tuple नहीं है। यह गणित की तरह समूह वाले parentheses में बस integer 5 है। एक item वाला tuple बनाने के लिए आख़िरी comma चाहिए: (5,)। Commas tuple बनाते हैं; parentheses बस पढ़ने में मदद करते हैं। बिना parentheses के 5, भी tuple है। आख़िरी line भी देखें: (x ** 2 for x in ...) एक generator है, tuple नहीं।
(5) 不是元组。它只是放在分组括号里的整数 5,就像数学里那样。要创建单元素元组,必须加末尾逗号:(5,)。造就元组的是逗号,括号只是方便阅读。连不带括号的 5, 也是元组。还要注意最后一行:(x ** 2 for x in ...) 是生成器,不是元组。
Pick an expression. Commas glow green; parentheses are grey. The type and value come from real Python.
कोई expression चुनें। Commas हरे चमकते हैं; parentheses धूसर हैं। Type और मान असली Python से आए हैं।
选择一个表达式。逗号显示为绿色,括号为灰色。类型和值来自真实的 Python。
How Tuples Are Stored in Memory 🧠Tuples Memory में कैसे रहते हैं 🧠元组如何存储在内存中 🧠
Like a list, a tuple holds references to objects that live elsewhere in memory. The big difference: a tuple's slots are locked. It cannot grow, shrink, or point a slot at a different object. Because its size never changes, CPython stores the references inside the tuple object itself, with no spare room.
List की तरह tuple भी memory में कहीं और रहने वाले objects के references रखता है। बड़ा अंतर: tuple के slots बंद हैं। यह न बढ़ सकता है, न घट सकता है, न किसी slot को दूसरे object की ओर कर सकता है। आकार कभी नहीं बदलता, इसलिए CPython references को tuple object के अंदर ही रखता है, बिना ख़ाली जगह के।
和列表一样,元组保存的是指向内存中其他对象的引用。最大的区别是:元组的槽位是锁定的。它不能变长、变短,也不能让某个槽位指向另一个对象。因为大小永不改变,CPython 把引用直接存放在元组对象内部,没有预留空间。
The Visual Modelचित्र से समझें图解模型
The red dashed border means locked: the slots can be read but never re-pointed.
लाल डैश वाली सीमा का मतलब बंद: slots पढ़े जा सकते हैं पर कभी दूसरी ओर नहीं किए जा सकते।
红色虚线边框表示锁定:槽位可以读取,但永远不能改指向。
Tuple vs List — The Memory LayoutTuple बनाम List — Memory की बनावट元组 vs 列表 —— 内存布局
Sizes are real sys.getsizeof() values on 64-bit Python 3.13.16.
आकार 64-bit Python 3.13.16 के असली sys.getsizeof() मान हैं।
大小为 64 位 Python 3.13.16 中真实的 sys.getsizeof() 值。
Measure It Yourselfख़ुद नापें亲自测一测
import sys, timeit
print("size in bytes (the container only):")
for n in (0, 3, 10):
t, l = tuple(range(n)), list(range(n))
print(f" {n:>2} items: tuple {sys.getsizeof(t):>3}, list {sys.getsizeof(l):>3}")
def best(stmt, setup="pass", number=1_000_000):
return min(timeit.repeat(stmt, setup, number=number, repeat=7))
print("time for 1,000,000 runs (best of 7):")
print(f" build (1, 2, 3, 4, 5): {best('(1, 2, 3, 4, 5)'):.3f} s")
print(f" build [1, 2, 3, 4, 5]: {best('[1, 2, 3, 4, 5]'):.3f} s")
setup = "t = tuple(range(100)); l = list(range(100))"
print(f" loop over 100-item tuple: {best('for x in t: pass', setup, 100_000) * 10:.3f} s")
print(f" loop over 100-item list: {best('for x in l: pass', setup, 100_000) * 10:.3f} s")
A tuple is always a little smaller (16 bytes less header, and no spare slots). Building the constant tuple (1, 2, 3, 4, 5) was about 3× faster than building the list (0.010 s vs 0.034 s), because Python builds a constant tuple once, when it compiles the code, and then just reuses it. Looping, however, took about the same time (0.571 s vs 0.572 s). So choose a tuple for its meaning and safety, not for loop speed.
Tuple हमेशा थोड़ा छोटा होता है (header में 16 bytes कम, और कोई ख़ाली slots नहीं)। स्थिर tuple (1, 2, 3, 4, 5) बनाना list बनाने से लगभग 3× तेज़ रहा (0.010 s बनाम 0.034 s), क्योंकि Python स्थिर tuple को code compile करते समय एक बार बनाकर बस दोबारा इस्तेमाल करता है। पर loop करने में लगभग उतना ही समय लगा (0.571 s बनाम 0.572 s)। इसलिए tuple उसके मतलब और सुरक्षा के लिए चुनें, loop की गति के लिए नहीं।
元组总是略小一些(头部少 16 字节,且没有空槽位)。创建常量元组 (1, 2, 3, 4, 5) 比创建列表快约 3 倍(0.010 秒 vs 0.034 秒),因为 Python 在编译代码时就把常量元组一次性建好,之后直接复用。但遍历所花的时间几乎相同(0.571 秒 vs 0.572 秒)。所以选择元组是为了它的含义和安全性,而不是循环速度。
What Happens If You Try to Change a TupleTuple बदलने की कोशिश करें तो क्या होता है尝试修改元组会发生什么
t = (10, 20, 30)
for attempt in ("t[0] = 99", "t.append(40)", "del t[0]"):
try:
exec(attempt)
except (TypeError, AttributeError) as err:
print(f"{attempt:<13} → {type(err).__name__}: {err}")
old = t
t = t + (40,) # builds a NEW tuple and rebinds the name
print(t, old, t is old)
data = ([1, 2], [3, 4])
data[0].append(99) # the LIST inside can change
print(data)
try:
data[0] = [7, 8, 9] # but the slot itself is locked
except TypeError as err:
print("TypeError:", err)
Notice the two different ideas. t = t + (40,) is fine: it builds a new tuple and moves the name t to it (t is old is False). And a list inside a tuple can still change, because the tuple only locks which object each slot points to — not the object itself.
दो अलग विचार देखें। t = t + (40,) ठीक है: यह एक नया tuple बनाता है और नाम t को उस पर ले जाता है (t is old False है)। और tuple के अंदर की list अब भी बदल सकती है, क्योंकि tuple सिर्फ़ यह बंद करता है कि हर slot किस object की ओर है — object को ख़ुद नहीं।
注意两个不同的概念。t = t + (40,) 是可以的:它构建一个新元组,并把名字 t 移过去(t is old 为 False)。而元组里面的列表仍然可以改变,因为元组锁定的只是每个槽位指向哪个对象 —— 而不是对象本身。
Start from t = (1, 2, [3, 4]). Each button runs one line in a fresh copy; the results come from real Python.
t = (1, 2, [3, 4]) से शुरू करें। हर button एक नई copy में एक line चलाता है; नतीजे असली Python के हैं।
从 t = (1, 2, [3, 4]) 开始。每个按钮在一个全新副本上运行一行代码;结果来自真实的 Python。
Why Use a Tuple? — Four Real Advantages 💡Tuple क्यों? — चार असली फ़ायदे 💡为什么用元组?—— 四个真正的优点 💡
distances = { # road distance in km (approx.)
("Delhi", "Agra"): 233,
("Delhi", "Jaipur"): 281,
("Agra", "Jaipur"): 239,
}
print(distances[("Delhi", "Agra")])
try:
bad = {["Delhi", "Agra"]: 233}
except TypeError as err:
print("TypeError:", err)
visited = {(0, 0), (1, 2), (3, 4)} # tuples can live in a set
print((1, 2) in visited)
try:
hash((1, [2, 3])) # a tuple is hashable only if its items are
except TypeError as err:
print("TypeError:", err)
def min_max(numbers):
return min(numbers), max(numbers) # returns ONE tuple
low, high = min_max([3, 1, 4, 1, 5, 9])
print(low, high, min_max([3, 1, 4]))
The second-to-last line shows the fine print: (1, [2, 3]) is a tuple, but it holds a list, so it cannot be hashed or used as a key.
आख़िरी से पहली line बारीक बात दिखाती है: (1, [2, 3]) tuple है, पर उसमें list है, इसलिए उसका hash नहीं बनता और वह key नहीं बन सकता।
倒数第二行说明了一个细节:(1, [2, 3]) 是元组,但它里面有列表,所以不能被哈希,也不能作键。
Tuple vs List — Side by Side ⚖️Tuple बनाम List — आमने-सामने ⚖️元组 vs 列表 —— 并排对比 ⚖️
| Propertyगुण特性 | Behaviourव्यवहार行为 |
|---|---|
| SyntaxSyntax语法 | [1, 2, 3] |
| Change after creationबनने के बाद बदलाव创建后修改 | Yesहाँ可以 |
| Add / remove itemsItems जोड़ना / हटाना增删项 | Yes — append, pop, …हाँ — append, pop, …可以 —— append、pop…… |
| Size of [1, 2, 3][1, 2, 3] का आकार[1, 2, 3] 的大小 | 88 bytes |
| Building a constant oneस्थिर वाला बनाना构建常量 | Built every timeहर बार बनती है每次都要构建 |
| Looping speedLoop की गति遍历速度 | About the sameलगभग बराबर差不多 |
| Hashable (dict / set)Hashable (dict / set)可哈希(字典 / 集合) | Noनहीं不可以 |
| MethodsMethods方法 | 11 |
| Use forकिसके लिए适用于 | Collections that grow, shrink or get sortedबढ़ने, घटने या sort होने वाले collections会增减或排序的集合 |
| Propertyगुण特性 | Behaviourव्यवहार行为 |
|---|---|
| SyntaxSyntax语法 | (1, 2, 3) orया或 1, 2, 3 |
| Change after creationबनने के बाद बदलाव创建后修改 | No — TypeErrorनहीं — TypeError不可以 —— TypeError |
| Add / remove itemsItems जोड़ना / हटाना增删项 | Noनहीं不可以 |
| Size of (1, 2, 3)(1, 2, 3) का आकार(1, 2, 3) 的大小 | 64 bytes |
| Building a constant oneस्थिर वाला बनाना构建常量 | Built once, reusedएक बार बनता, दोबारा इस्तेमाल只建一次,重复使用 |
| Looping speedLoop की गति遍历速度 | About the sameलगभग बराबर差不多 |
| Hashable (dict / set)Hashable (dict / set)可哈希(字典 / 集合) | Yes, if every item isहाँ, अगर हर item हो可以,前提是每项都可哈希 |
| MethodsMethods方法 | 2: count(), index() |
| Use forकिसके लिए适用于 | Fixed records, coordinates, return values, dict keysतय records, coordinates, लौटे मान, dict keys固定记录、坐标、返回值、字典键 |
Tuple for a fixed group where each position has a meaning — a coordinate, an RGB colour, a database row, a function's several return values.
List for a collection you expect to grow, shrink, sort or filter — a shopping cart, search results, a to-do list.
Quick test: if you say "these values belong together", use a tuple; if you say "here is a bunch of similar things", use a list.
Tuple तय समूह के लिए जहाँ हर जगह का एक मतलब हो — coordinate, RGB रंग, database की row, function के कई लौटे मान।
List ऐसे collection के लिए जो बढ़ेगा, घटेगा, sort या filter होगा — shopping cart, search नतीजे, to-do list।
जल्दी की जाँच: अगर आप कहते हैं "ये मान साथ के हैं", तो tuple; अगर कहते हैं "ये एक जैसी कई चीज़ें हैं", तो list।
元组用于每个位置都有特定含义的固定组合 —— 坐标、RGB 颜色、数据库的一行、函数的多个返回值。
列表用于会增加、减少、排序或过滤的集合 —— 购物车、搜索结果、待办事项。
快速判断:如果你在说“这些值属于一组”,用元组;如果你在说“这是一堆同类的东西”,用列表。
Indexing — Reaching One Item 🎯Indexing — एक Item तक पहुँचना 🎯索引 —— 取到单个项 🎯
Tuples are ordered, so every item has a numbered position. As with lists and strings, Python counts from zero and also accepts negative indexes, which count from the end. Reading works; assigning does not.
Tuples क्रमबद्ध हैं, इसलिए हर item की एक गिनती वाली जगह है। Lists और strings की तरह Python शून्य से गिनता है और अंत से गिनने वाले negative indexes भी लेता है। पढ़ना चलता है; assign करना नहीं।
元组是有序的,所以每一项都有编号位置。与列表和字符串一样,Python 从零开始数,也接受从末尾数的负索引。读取可以,赋值不行。
Blue = counting from the left (0, 1, 2…). Red = counting from the right (-1 is the last item).
नीला = बाएँ से गिनती (0, 1, 2…)। लाल = दाएँ से गिनती (-1 आख़िरी item)।
蓝色 = 从左数(0、1、2……)。红色 = 从右数(-1 是最后一项)。
rgb = ("red", 255, 128, 0, "hex:#FF8000")
print(rgb[0], rgb[3], rgb[-1], rgb[-4])
print(len(rgb), 128 in rgb, "green" in rgb)
try:
rgb[0] = "blue"
except TypeError as err:
print("TypeError:", err)
mixed = (1, 2, [3, 4])
mixed[2].append(5) # mutating the inner list is allowed
print(mixed)
Slicing — Taking Sub-Tuples ✂️Slicing — छोटे Tuples निकालना ✂️切片 —— 取出子元组 ✂️
Slicing works exactly as it does for lists and strings, and the result is always a tuple. Out-of-range numbers never crash. Slice assignment, which lists allow, is blocked for tuples.
Slicing lists और strings जैसी ही चलती है, और नतीजा हमेशा tuple होता है। सीमा से बाहर के अंक कभी नहीं रोकते। Slice assignment, जो lists में चलता है, tuples में रोका गया है।
切片与列表、字符串完全相同,结果总是元组。越界数字永不报错。列表允许的切片赋值,元组不允许。
nums = (10, 20, 30, 40, 50, 60, 70, 80)
print(nums[2:5], nums[:3], nums[5:])
print(nums[-3:], nums[:-2])
print(nums[::2], nums[::-1])
print(nums[100:200], type(nums[2:5]).__name__)
print(nums[:] is nums) # CPython returns the SAME tuple — no copy needed
try:
nums[1:4] = (99, 99)
except TypeError as err:
print("TypeError:", err)
| PatternPattern写法 | Meaningमतलब含义 | Example on (10, 20, 30, 40, 50)(10, 20, 30, 40, 50) पर उदाहरण在 (10, 20, 30, 40, 50) 上的示例 |
|---|---|---|
| t[a:b] | Indexes a to b-1 (a new tuple)Index a से b-1 तक (नया tuple)索引 a 到 b-1(新元组) | t[1:4] → (20, 30, 40) |
| t[:n] | First n itemsपहले n items前 n 项 | t[:3] → (10, 20, 30) |
| t[n:] | From index n to the endIndex n से अंत तक从索引 n 到末尾 | t[3:] → (40, 50) |
| t[-n:] | Last n itemsआख़िरी n items最后 n 项 | t[-2:] → (40, 50) |
| t[::-1] | Reversed (a new tuple)उल्टा (नया tuple)反转(新元组) | t[::-1] → (50, 40, 30, 20, 10) |
| t[:] | The whole tuple — CPython hands back the SAME objectपूरा tuple — CPython वही object लौटाता है整个元组 —— CPython 直接返回同一个对象 | t[:] is t → True |
For a list, lst[:] makes a fresh copy. For a tuple, t[:] gives back the same object — there is no reason to copy something that can never change. The output above shows nums[:] is nums → True. This is a CPython detail, so never write code that depends on it.
List के लिए lst[:] नई copy बनाता है। Tuple के लिए t[:] वही object लौटाता है — जो कभी बदल नहीं सकता, उसकी copy बनाने का कोई कारण नहीं। ऊपर का output nums[:] is nums → True दिखाता है। यह CPython की अंदरूनी बात है, इसलिए ऐसा code कभी न लिखें जो इस पर निर्भर हो।
对列表来说,lst[:] 会生成新副本。对元组来说,t[:] 返回的是同一个对象 —— 永远不会变的东西没必要复制。上面的输出显示 nums[:] is nums → True。这是 CPython 的实现细节,所以不要写依赖它的代码。
Tuple Methods — Only Two Exist 🧰Tuple Methods — सिर्फ़ दो हैं 🧰元组方法 —— 只有两个 🧰
Because a tuple cannot change, it needs only 2 methods: .count() and .index(). Both just read. There is no append, sort or reverse — those would need to change the tuple. The last line of the output below lists them straight from dir(tuple).
Tuple बदल नहीं सकता, इसलिए उसे सिर्फ़ 2 methods चाहिए: .count() और .index()। दोनों बस पढ़ते हैं। न append है, न sort, न reverse — इनके लिए tuple को बदलना पड़ता। नीचे output की आख़िरी line इन्हें सीधे dir(tuple) से दिखाती है।
因为元组不能改变,它只需要 2 个方法:.count() 和 .index()。两者都只读取。没有 append、sort 或 reverse —— 它们都需要修改元组。下面输出的最后一行直接从 dir(tuple) 列出了它们。
votes = ("yes", "no", "yes", "yes", "no", "abstain")
print(votes.count("yes"), votes.count("no"), votes.count("maybe"))
print(votes.index("no"), votes.index("abstain"))
try:
votes.index("maybe")
except ValueError as err:
print("ValueError:", err)
scores = (88, 75, 92, 60, 83)
print(len(scores), min(scores), max(scores), sum(scores))
print(sorted(scores)) # sorted() always returns a LIST
print(tuple(sorted(scores))) # convert back for a tuple
print((1, 2) + (3,), (0,) * 3) # + and * build NEW tuples
print([m for m in dir(tuple) if not m.startswith("_")])
| Groupसमूह类别 | OperationOperation操作 | What it doesक्या करता है作用 | Returnsलौटाता है返回 |
|---|---|---|---|
| MethodsMethods方法 | .count(x) | How many items equal xकितने items x के बराबर等于 x 的项数 | int |
| .index(x) | Position of the first item equal to xx के बराबर पहले item की जगह第一个等于 x 的项的位置 | int / ValueError | |
| Built-insBuilt-ins内置函数 | len(t) | Number of itemsItems की गिनती项数 | int |
| min(t) / max(t) | Smallest / largest itemसबसे छोटा / बड़ा item最小 / 最大项 | an itemएक item一项 | |
| sum(t) | Total of the numbersसंख्याओं का जोड़数字之和 | int / float | |
| sorted(t) | A new sorted list (not a tuple!)नई sorted list (tuple नहीं!)新的已排序列表(不是元组!) | list | |
| x in t | Membership testसदस्यता जाँच成员检测 | bool | |
| OperatorsOperators运算符 | t1 + t2 | Join two tuplesदो tuples जोड़ें拼接两个元组 | new tupleनया tuple新元组 |
| t * n | Repeat n timesn बार दोहराएँ重复 n 次 | new tupleनया tuple新元组 |
Packing & Unpacking — Python's Superpower 🎁Packing और Unpacking — Python की ख़ास ताक़त 🎁打包与拆包 —— Python 的超能力 🎁
This is where tuples shine. Multiple assignment, returning several values, swapping two variables and looping over pairs all use tuple packing (putting values together) and unpacking (taking them apart) behind the scenes.
यहीं tuples चमकते हैं। एक साथ कई assignment, कई मान लौटाना, दो variables की अदला-बदली, और जोड़ियों पर loop — ये सब परदे के पीछे tuple packing (मानों को साथ रखना) और unpacking (उन्हें अलग करना) लगाते हैं।
这正是元组大放异彩的地方。多重赋值、返回多个值、交换两个变量、遍历成对数据 —— 背后都在使用元组打包(把值放在一起)和拆包(把它们分开)。
point = 3, 4 # packing
person = "Asha", 30, "Pune"
print(type(point).__name__, person)
x, y = point # unpacking
print(x, y)
try:
a, b = (1, 2, 3)
except ValueError as err:
print("ValueError:", err)
a, b = 5, 10
a, b = b, a # swap: pack the right, unpack on the left
print(a, b)
numbers = (1, 2, 3, 4, 5)
first, *rest = numbers
*init, last = numbers
head, *middle, tail = numbers
print(first, rest, init, last)
print(head, middle, tail) # the starred name always gets a LIST
name, age, _, _ = ("Asha", 30, "Pune", "engineer")
print(name, age)
record = ("Asha", (18.5204, 73.8567))
name, (lat, lon) = record # nested unpacking
print(f"{name} at {lat}, {lon}")
Pick a pattern and change the tuple length. Colours show where each item goes. Try 1 or 0 items to see the errors, or the swap.
कोई pattern चुनें और tuple की लंबाई बदलें। रंग बताते हैं कि हर item कहाँ जाता है। Errors देखने के लिए 1 या 0 items आज़माएँ, या swap।
选择一种写法并改变元组长度。颜色显示每一项去了哪里。试试 1 或 0 项看看报错,或者试试交换。
Multiple Return Values — Tuples Under the Hoodकई लौटे मान — परदे के पीछे Tuples多个返回值 —— 背后是元组
def divmod_custom(a, b):
return a // b, a % b # actually returns ONE tuple
result = divmod_custom(17, 5)
print(result, type(result).__name__)
quotient, remainder = divmod_custom(17, 5)
print(quotient, remainder)
print(divmod(17, 5)) # the built-in does the same
Every time you write x, y = 3, 4, Python packs the right side into the tuple (3, 4) and then unpacks it into x and y. That is why swapping is one line: a, b = b, a — the right side is fully worked out before anything on the left is changed. Once this clicks, much of Python's syntax feels obvious.
जब भी आप x, y = 3, 4 लिखते हैं, Python दाएँ हिस्से को tuple (3, 4) में pack करता है और फिर उसे x और y में unpack करता है। इसीलिए अदला-बदली एक line है: a, b = b, a — बाईं ओर कुछ बदलने से पहले दायाँ हिस्सा पूरा निकाल लिया जाता है। यह समझ आते ही Python का बहुत सा syntax साफ़ लगने लगता है।
每当你写 x, y = 3, 4,Python 都会把右边打包成元组 (3, 4),再拆包到 x 和 y。这就是交换只需一行的原因:a, b = b, a —— 右边会在左边有任何改变之前完全算好。想通这一点,Python 的很多语法都会变得一目了然。
The for Loop — Walking Through Tuples 🔄for Loop — Tuples में चलना 🔄for 循环 —— 遍历元组 🔄
Looping over a tuple works just like looping over a list. And because a tuple cannot change, you cannot accidentally change it in the middle of a loop.
Tuple पर loop बिल्कुल list जैसा चलता है। और tuple बदल नहीं सकता, इसलिए loop के बीच गलती से उसे बदल भी नहीं सकते।
遍历元组和遍历列表完全一样。而且元组不能改变,所以你也不可能在循环中途意外修改它。
Patterns 1 and 2 — Values, and Values With an IndexPatterns 1 और 2 — मान, और Index के साथ मान模式 1 和 2 —— 取值,以及带索引取值
colors = ("red", "green", "blue")
for color in colors:
print(f"Rendering {color}")
for i, color in enumerate(colors):
print(f"{i}: {color}")
print(list(enumerate(colors))) # enumerate gives (index, value) tuples
The last line shows the secret: enumerate() hands out (index, value) tuples, and for i, color in ... unpacks each one.
आख़िरी line राज़ बताती है: enumerate() (index, value) tuples देता है, और for i, color in ... हर एक को unpack करता है।
最后一行揭示了秘密:enumerate() 产出的是 (索引, 值) 元组,for i, color in ... 把每个元组拆包。
Pattern 3 — A Tuple of Tuples (a Table of Records)Pattern 3 — Tuples का Tuple (Records की Table)模式 3 —— 元组的元组(记录表)
A tuple of tuples is a light, read-only table. Unpacking each record as you loop reads almost like English.
Tuples का tuple एक हल्की, सिर्फ़ पढ़ने वाली table है। Loop करते हुए हर record को unpack करना लगभग अंग्रेज़ी जैसा पढ़ा जाता है।
元组的元组是一张轻量、只读的表。遍历时拆包每条记录,读起来几乎像英语。
students = (
("Asha", 92, "A"),
("Ravi", 78, "C"),
("Meena", 85, "B"),
("Dev", 60, "D"),
)
for name, score, grade in students:
print(f"{name:<6} scored {score} → grade {grade}")
top = [name for name, score, _ in students if score >= 85]
print(top)
s[1] does not say what it holds. For records with several fields, collections.namedtuple gives each position a name, so you can write s.score — and it is still a tuple, with the same size and safety.
s[1] नहीं बताता कि उसमें क्या है। कई fields वाले records के लिए collections.namedtuple हर जगह को एक नाम देता है, ताकि आप s.score लिख सकें — और यह अब भी tuple है, उतने ही आकार और सुरक्षा के साथ।
s[1] 看不出装的是什么。对于有多个字段的记录,collections.namedtuple 给每个位置起一个名字,于是你可以写 s.score —— 而它仍然是元组,大小和安全性不变。
Patterns 4 and 5 — zip() and dict.items()Patterns 4 और 5 — zip() और dict.items()模式 4 和 5 —— zip() 与 dict.items()
names = ("Asha", "Ravi", "Meena")
scores = (92, 78, 85)
for name, score in zip(names, scores):
print(f"{name}: {score}")
pairs = tuple(zip(names, scores))
print(pairs)
ages = {"Asha": 30, "Ravi": 25, "Meena": 35}
for name, age in ages.items(): # .items() gives (key, value) tuples
print(f"{name} is {age}")
print(list(ages.items()))
Both zip() and dict.items() hand out tuples — (name, score) and (key, value) — which the loop unpacks for you.
zip() और dict.items() दोनों tuples देते हैं — (name, score) और (key, value) — जिन्हें loop आपके लिए unpack करता है।
zip() 和 dict.items() 都产出元组 —— (name, score) 和 (key, value) —— 循环会替你拆包。
Complete Practice Program — GPS Waypoints 🧭पूरा अभ्यास Program — GPS Waypoints 🧭完整练习程序 —— GPS 航点 🧭
This program uses tuple records, nested unpacking, enumerate(), zip() over a tuple and its slice, a function that returns four values, and tuples as dictionary keys. We also print each leg of the path so you can check the total.
यह program tuple records, nested unpacking, enumerate(), tuple और उसकी slice पर zip(), चार मान लौटाने वाला function, और dictionary keys के रूप में tuples लगाता है। हम रास्ते का हर हिस्सा भी छापते हैं ताकि आप कुल दूरी जाँच सकें।
这个程序用到了元组记录、嵌套拆包、enumerate()、对元组及其切片使用 zip()、返回四个值的函数,以及用元组作字典键。我们还打印了路径的每一段,方便你核对总长度。
# waypoints.py — every tuple concept in one program
import math
def distance(p1, p2):
"""Straight-line distance between two (x, y) tuples."""
x1, y1 = p1 # unpacking!
x2, y2 = p2
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def bounding_box(points):
"""Return (min_x, min_y, max_x, max_y) — a tuple of 4 values."""
xs = tuple(x for x, _ in points)
ys = tuple(y for _, y in points)
return min(xs), min(ys), max(xs), max(ys)
def main():
# A tuple of waypoint records: (name, (x, y))
waypoints = (
("Start", (0.0, 0.0)),
("Checkpoint A", (3.0, 4.0)),
("Checkpoint B", (6.0, 8.0)),
("Peak", (10.0, 6.0)),
("Finish", (15.0, 0.0)),
)
line = "─" * 36
print(f"{line}\n WAYPOINT TRACKER\n{line}")
# Loop + unpack each record
print(f" {'#':>2} {'NAME':<15}{'COORDS':>13}")
for i, (name, coords) in enumerate(waypoints, 1):
print(f" {i:>2} {name:<15}{str(coords):>13}")
# Total path: pair each point with the next one
total = 0.0
for (_, p1), (_, p2) in zip(waypoints, waypoints[1:]):
leg = distance(p1, p2)
total += leg
print(f" {str(p1):>11} → {str(p2):<11} {leg:5.2f}")
print(f" Total path length: {total:.2f} units")
# Indexing & slicing
print(f"\n First waypoint: {waypoints[0][0]}")
print(f" Last waypoint: {waypoints[-1][0]}")
print(f" Middle 3: {tuple(w[0] for w in waypoints[1:-1])}")
# Bounding box (multiple return via a tuple)
coords_only = tuple(c for _, c in waypoints)
min_x, min_y, max_x, max_y = bounding_box(coords_only)
print(f"\n Bounding box: ({min_x}, {min_y}) → ({max_x}, {max_y})")
# Tuples as dict keys
labels = {c: n for n, c in waypoints}
lookup = (10.0, 6.0)
print(f" What's at {lookup}? → {labels.get(lookup, 'unknown')}")
# Prove immutability
try:
waypoints[0] = ("Hacked", (0, 0))
except TypeError as e:
print(f"\n Tuple protects its data: {e}")
if __name__ == "__main__":
main()
The four legs are 5.00 + 5.00 + 4.47 + 7.81 = 22.28 units (for example, from (6, 8) to (10, 6) is √(4² + 2²) = √20 ≈ 4.47). zip(waypoints, waypoints[1:]) is the trick that pairs each point with the next one.
चारों हिस्से 5.00 + 5.00 + 4.47 + 7.81 = 22.28 units हैं (जैसे (6, 8) से (10, 6) तक √(4² + 2²) = √20 ≈ 4.47)। zip(waypoints, waypoints[1:]) वह तरकीब है जो हर point को अगले से जोड़ती है।
四段距离为 5.00 + 5.00 + 4.47 + 7.81 = 22.28 个单位(例如从 (6, 8) 到 (10, 6) 是 √(4² + 2²) = √20 ≈ 4.47)。zip(waypoints, waypoints[1:]) 就是把每个点和下一个点配对的技巧。
Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆
Six questions on tuples. Pick an answer to see why.
Tuples पर छह सवाल। जवाब चुनें और कारण देखें।
关于元组的六道题。选择答案查看解释。
A tuple is an ordered, immutable sequence, made by commas (one item needs (x,)). Its slots are locked, which makes it a little smaller, safe to share and — when its items allow — usable as a dict key. Read it with indexing and slicing, query it with count() and index(), and use packing and unpacking for swaps, multiple return values and clean loops. Use a tuple for a record and a list for a collection.
Tuple एक क्रमबद्ध, न बदलने वाला sequence है, जो commas से बनता है (एक item के लिए (x,))। इसके slots बंद हैं, जिससे यह थोड़ा छोटा, साझा करने में सुरक्षित, और — जब items अनुमति दें — dict key बनने लायक़ है। इसे indexing और slicing से पढ़ें, count() और index() से जाँचें, और अदला-बदली, कई लौटे मानों और साफ़ loops के लिए packing और unpacking लगाएँ। Record के लिए tuple, collection के लिए list।
元组是由逗号创建的有序、不可变序列(单元素要写 (x,))。它的槽位是锁定的,这让它更小一些、可以放心共享,并且(在各项允许时)能作字典键。用索引和切片读取,用 count() 和 index() 查询,用打包和拆包来交换变量、返回多个值、写出简洁的循环。记录用元组,集合用列表。