BASIC Python (Beginner Level) 📂 Basic Python Programming · 9 of 15 140 min read

Python Tuples - Memory Model, Indexing, Slicing, Methods, Unpacking & For Loops

Master Python tuples from the ground up. This tutorial explains how tuples are stored in memory as immutable arrays of references (with animated diagrams), the single-element trap, tuple vs list side-by-side comparison, positive and negative indexing, complete slicing syntax, the only two methods count and index, tuple packing and unpacking including star unpacking and swapping, five for-loop patterns, and a full GPS-waypoint practice program.

🌐
SectionSection第 01 节

The Story That Explains Tuples ✉️Tuples समझाने वाली कहानी ✉️一个解释元组的故事 ✉️

A Sealed Envelope of RecordsRecords का मुहरबंद लिफ़ाफ़ा封好的档案信封
Imagine a government office that hands you a sealed birth-certificate envelope. Inside are fixed facts: name, date, city, hospital. Once sealed, the envelope is tamper-proof. You can read it, copy it and pass it around — but you cannot change "Pune" to "Delhi" without throwing it away and getting a brand-new document.

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.
सोचिए किसी सरकारी दफ़्तर ने आपको जन्म-प्रमाणपत्र का मुहरबंद लिफ़ाफ़ा दिया। अंदर तय जानकारी है: नाम, तारीख़, शहर, अस्पताल। मुहर लगने के बाद लिफ़ाफ़े से छेड़छाड़ नहीं हो सकती। आप उसे पढ़ सकते हैं, उसकी copy कर सकते हैं, आगे दे सकते हैं — पर "Pune" को "Delhi" नहीं कर सकते, जब तक उसे फेंककर बिल्कुल नया दस्तावेज़ न बनवाएँ।

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 से लौटे कई मान।
想象政府办公室交给你一个封好的出生证明信封。里面是固定的信息:姓名、日期、城市、医院。封好之后,信封就无法被篡改。你可以阅读、复印、传递它 —— 但不能把 "Pune" 改成 "Delhi",除非扔掉它重新办一份全新的证件。

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 内置的有序、不可变序列。有序是指位置很重要;不可变是指创建后不能修改。可以把元组看作列表更严格的兄弟:功能更少,保证更多。

📑
Orderedक्रमबद्ध有序
position mattersजगह मायने रखती है位置很重要
Items stay in the order you put them. Index 0 is always index 0. That is what makes indexing, slicing and looping work.
Items उसी क्रम में रहते हैं जिसमें रखे। Index 0 हमेशा index 0 है। इसी से indexing, slicing और looping काम करते हैं।
各项保持放入时的顺序。索引 0 永远是索引 0。索引、切片和循环正依赖于此。
🔒
ImmutableImmutable不可变
cannot changeबदल नहीं सकता不能修改
Once made, you cannot add, remove or replace items. Any "change" builds a brand-new tuple. This is the key difference from lists.
बनने के बाद आप items जोड़, हटा या बदल नहीं सकते। हर "बदलाव" एक नया tuple बनाता है। Lists से यही मुख्य अंतर है।
创建后不能添加、删除或替换项。任何“修改”都会生成一个全新的元组。这是与列表的关键区别。
🎗
Any Typeकोई भी Type任意类型
mix freelyखुलकर मिलाएँ自由混合
Like a list, a tuple can mix types: ("Asha", 30, 5.4) groups a name, an age and a height.
List की तरह tuple में भी types मिल सकते हैं: ("Asha", 30, 5.4) नाम, उम्र और क़द को साथ रखता है।
和列表一样,元组可以混合类型:("Asha", 30, 5.4) 把名字、年龄和身高放在一起。
▶️
This Tutorial Has Three Simulatorsइस Tutorial में तीन Simulators हैं本教程有三个模拟器

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 生成。


SectionSection第 02 节

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__)
OUTPUT
() (28.6139, 77.209) (255, 128, 0) ('Asha', 30, 5.4, True) ((1, 2), (3, 4), (5, 6)) (3, 4) ('Ravi', 25) int tuple (5,) (1, 2, 3) ('h', 'e', 'l', 'l', 'o') (0, 1, 2, 3, 4) (1, 4, 9, 16, 25) generator
⚠️
The One-Item Trap — Memorise Thisएक Item वाला जाल — इसे याद कर लें单元素陷阱 —— 一定要记住

(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 ...) 是生成器,不是元组。

LIVELIVE互动Comma Detector — what makes a tuple?Comma Detector — tuple किससे बनता है?逗号探测器 —— 是什么造就了元组?

Pick an expression. Commas glow green; parentheses are grey. The type and value come from real Python.

कोई expression चुनें। Commas हरे चमकते हैं; parentheses धूसर हैं। Type और मान असली Python से आए हैं।

选择一个表达式。逗号显示为绿色,括号为灰色。类型和值来自真实的 Python。


SectionSection第 03 节

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चित्र से समझें图解模型

🔒 point = (28.6139, 77.209, "Delhi") in memory🔒 Memory में point = (28.6139, 77.209, "Delhi")🔒 内存中的 point = (28.6139, 77.209, "Delhi")
How a tuple is stored in memorypointvariablevariable变量TUPLE OBJECT — locked references, stored inside itTUPLE OBJECT — बंद references, उसी के अंदर元组对象 —— 锁定的引用,存放在其内部[0]ref[1]ref[2]reflen 3 · 64 bytes · no spare room, can never growlen 3 · 64 bytes · कोई ख़ाली जगह नहीं, कभी नहीं बढ़ताlen 3 · 64 字节 · 没有预留空间,永远不会变长HEAP:HEAP:堆:the valuesअसली मान真正的值live hereयहाँ रहते हैं住在这里28.6139float77.209float"Delhi"str

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 列表 —— 内存布局

📦 Where the references live📦 References कहाँ रहते हैं📦 引用存放在哪里
Tuple vs list memory layoutLIST [1, 2, 3]LIST [1, 2, 3]列表 [1, 2, 3]headerheader头部len 3room for 44 की जगह容量 4pointer →pointer →指针 →refrefref–separate array (+1 spare)अलग array (+1 ख़ाली)独立数组(+1 空位)88 bytes88 bytes88 字节TUPLE (1, 2, 3)TUPLE (1, 2, 3)元组 (1, 2, 3)headerheader头部len 3refrefrefrefs stored inline, exact sizerefs अंदर ही, ठीक उतना आकार引用内联存放,大小刚好64 bytes64 bytes64 字节Same reference idea — but the tuple is 27% smaller here and can never be resized.Reference का वही विचार — पर यहाँ tuple 27% छोटा है और कभी resize नहीं होता।同样的引用设计 —— 但这里元组小 27%,而且永远不会调整大小。(sys.getsizeof counts the container only, not the items it points to)(sys.getsizeof सिर्फ़ container गिनता है, items नहीं)(sys.getsizeof 只计算容器本身,不含所指向的项)

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")
OUTPUT (YOUR TIMES WILL DIFFER)OUTPUT (आपके समय अलग होंगे)OUTPUT(你的耗时会不同)
size in bytes (the container only): 0 items: tuple 40, list 56 3 items: tuple 64, list 88 10 items: tuple 120, list 136 time for 1,000,000 runs (best of 7): build (1, 2, 3, 4, 5): 0.010 s build [1, 2, 3, 4, 5]: 0.034 s loop over 100-item tuple: 0.571 s loop over 100-item list: 0.572 s
⏱️
What the Numbers Really Sayअंक असल में क्या कहते हैं这些数字到底说明了什么

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[0] = 99⛔ t[0] = 99⛔ t[0] = 99
Attempt to change a tuplet = (10, 20, 30); t[0] = 99102030TypeError: 'tuple' object does not support item assignmentPython refuses. The tuple stays exactly as it was.Python मना कर देता है। Tuple जैसा था वैसा रहता है।Python 拒绝执行,元组保持原样。
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)
OUTPUT
t[0] = 99 → TypeError: 'tuple' object does not support item assignment t.append(40) → AttributeError: 'tuple' object has no attribute 'append' del t[0] → TypeError: 'tuple' object doesn't support item deletion (10, 20, 30, 40) (10, 20, 30) False ([1, 2, 99], [3, 4]) TypeError: 'tuple' object does not support item assignment

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)。而元组里面的列表仍然可以改变,因为元组锁定的只是每个槽位指向哪个对象 —— 而不是对象本身。

LIVELIVE互动Mutation Lab — what can change?Mutation Lab — क्या बदल सकता है?修改实验室 —— 什么可以改变?

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。


SectionSection第 04 节

Why Use a Tuple? — Four Real Advantages 💡Tuple क्यों? — चार असली फ़ायदे 💡为什么用元组?—— 四个真正的优点 💡

⚡
Smaller, Quick to Buildछोटा, जल्दी बनता है更小,构建更快
64 vs 88 bytes for 3 items3 items के लिए 64 बनाम 88 bytes3 项:64 对 88 字节
No growth logic and no spare slots, so a tuple uses less memory. Constant tuples are built once at compile time. Looping over a tuple, though, is about as fast as over a list.
न बढ़ने का logic, न ख़ाली slots, इसलिए tuple कम memory लेता है। स्थिर tuples compile के समय एक बार बनते हैं। पर tuple पर loop करना list जितना ही तेज़ है।
没有增长逻辑、没有空槽位,所以元组占用更少内存。常量元组在编译时就一次建好。不过遍历元组和遍历列表一样快。
🔑
Hashable → Dict Keys & SetsHashable → Dict Keys और Sets可哈希 → 字典键与集合
only if every item is hashableतभी जब हर item hashable हो前提:每一项都可哈希
Because a tuple cannot change, Python can compute a hash from its contents. So tuples work as dictionary keys and set members — great for coordinates, caching and two-part keys. Lists cannot.
Tuple बदल नहीं सकता, इसलिए Python उसकी सामग्री से hash निकाल सकता है। इसलिए tuples dictionary keys और set के सदस्य बन सकते हैं — coordinates, caching और दो-हिस्सों वाली keys के लिए बढ़िया। Lists नहीं बन सकतीं।
因为元组不能改变,Python 可以根据其内容计算哈希。所以元组可以作为字典键和集合成员 —— 非常适合坐标、缓存和组合键。列表做不到。
🔒
Data IntegrityData की सुरक्षा数据完整性
safe to pass aroundआगे देना सुरक्षित放心传递
When you return a tuple or pass one to a function, you know nobody can change it. A whole class of "who changed my data?" bugs disappears.
जब आप tuple लौटाते हैं या किसी function को देते हैं, तो आप जानते हैं कि कोई उसे बदल नहीं सकता। "मेरा data किसने बदला?" वाले bugs की पूरी श्रेणी ग़ायब हो जाती है।
当你返回一个元组或把它传给函数时,你知道没人能修改它。一整类“谁改了我的数据?”的 bug 就此消失。
🔁
Multiple Return Valuesकई मान लौटाना多个返回值
Python's return trickPython की return चालPython 的返回技巧
A function that "returns several values" really returns one tuple. return x, y packs it; the caller unpacks it.
जो function "कई मान लौटाता" है, वह असल में एक tuple लौटाता है। return x, y उसे pack करता है; call करने वाला unpack करता है।
“返回多个值”的函数实际上返回的是一个元组。return x, y 把它打包,调用者再拆包。
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]))
OUTPUT
233 TypeError: unhashable type: 'list' True TypeError: unhashable type: 'list' 1 9 (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]) 是元组,但它里面有列表,所以不能被哈希,也不能作键。


SectionSection第 05 节

Tuple vs List — Side by Side ⚖️Tuple बनाम List — आमने-सामने ⚖️元组 vs 列表 —— 并排对比 ⚖️

🔧 list — mutablelist — mutablelist —— 可变
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会增减或排序的集合
🔒 tuple — immutabletuple — immutabletuple —— 不可变
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固定记录、坐标、返回值、字典键
🔑
Which Should You Reach For?कौन सा चुनें?该选哪一个?

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 颜色、数据库的一行、函数的多个返回值。
列表用于会增加、减少、排序或过滤的集合 —— 购物车、搜索结果、待办事项。
快速判断:如果你在说“这些值属于一组”,用元组;如果你在说“这是一堆同类的东西”,用列表。


SectionSection第 06 节

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 从零开始数,也接受从末尾数的负索引。读取可以,赋值不行。

🎯 Positive and negative indexes🎯 Positive और negative indexes🎯 正索引与负索引
Tuple indexingrgb = ("red", 255, 128, 0, "hex:#FF8000")"red"0-52551-41282-303-2"hex:…"4-1Reading works exactly like a list — assignment is blockedपढ़ना बिल्कुल list जैसा — assign करना रोका गया读取与列表完全相同 —— 赋值被禁止

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)
OUTPUT
red 0 hex:#FF8000 255 5 True False TypeError: 'tuple' object does not support item assignment (1, 2, [3, 4, 5])

SectionSection第 07 节

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)
OUTPUT
(30, 40, 50) (10, 20, 30) (60, 70, 80) (60, 70, 80) (10, 20, 30, 40, 50, 60) (10, 30, 50, 70) (80, 70, 60, 50, 40, 30, 20, 10) () tuple True TypeError: 'tuple' object does not support item assignment
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
💡
A Curious Shortcutएक दिलचस्प shortcut一个有趣的捷径

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 的实现细节,所以不要写依赖它的代码。


SectionSection第 08 节

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("_")])
OUTPUT
3 2 0 1 5 ValueError: tuple.index(x): x not in tuple 5 60 92 398 [60, 75, 83, 88, 92] (60, 75, 83, 88, 92) (1, 2, 3) (0, 0, 0) ['count', 'index']
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 tMembership testसदस्यता जाँच成员检测bool
OperatorsOperators运算符t1 + t2Join two tuplesदो tuples जोड़ें拼接两个元组new tupleनया tuple新元组
t * nRepeat n timesn बार दोहराएँ重复 n 次new tupleनया tuple新元组

SectionSection第 09 节

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}")
OUTPUT
tuple ('Asha', 30, 'Pune') 3 4 ValueError: too many values to unpack (expected 2) 10 5 1 [2, 3, 4, 5] [1, 2, 3, 4] 5 1 [2, 3, 4] 5 Asha 30 Asha at 18.5204, 73.8567
LIVELIVE互动Unpacking Lab — who gets which item?Unpacking Lab — किसे कौन सा item मिलता है?拆包实验室 —— 哪个名字得到哪一项?

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
OUTPUT
(3, 2) tuple 3 2 (3, 2)
🎯
Two Sides of the Same Coinएक ही सिक्के के दो पहलू一枚硬币的两面

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 的很多语法都会变得一目了然。


SectionSection第 10 节

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
OUTPUT
Rendering red Rendering green Rendering blue 0: red 1: green 2: blue [(0, 'red'), (1, 'green'), (2, 'blue')]

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)
OUTPUT
Asha scored 92 → grade A Ravi scored 78 → grade C Meena scored 85 → grade B Dev scored 60 → grade D ['Asha', 'Meena']
🏷️
When Records Get Bigger: namedtupleजब Records बड़े हों: namedtuple记录变大时:namedtuple

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()))
OUTPUT
Asha: 92 Ravi: 78 Meena: 85 (('Asha', 92), ('Ravi', 78), ('Meena', 85)) Asha is 30 Ravi is 25 Meena is 35 [('Asha', 30), ('Ravi', 25), ('Meena', 35)]

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) —— 循环会替你拆包。


SectionSection第 11 节

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()
OUTPUT
──────────────────────────────────── WAYPOINT TRACKER ──────────────────────────────────── # NAME COORDS 1 Start (0.0, 0.0) 2 Checkpoint A (3.0, 4.0) 3 Checkpoint B (6.0, 8.0) 4 Peak (10.0, 6.0) 5 Finish (15.0, 0.0) (0.0, 0.0) → (3.0, 4.0) 5.00 (3.0, 4.0) → (6.0, 8.0) 5.00 (6.0, 8.0) → (10.0, 6.0) 4.47 (10.0, 6.0) → (15.0, 0.0) 7.81 Total path length: 22.28 units First waypoint: Start Last waypoint: Finish Middle 3: ('Checkpoint A', 'Checkpoint B', 'Peak') Bounding box: (0.0, 0.0) → (15.0, 8.0) What's at (10.0, 6.0)? → Peak Tuple protects its data: 'tuple' object does not support item assignment
🧮
Check the Arithmeticगणित जाँचें核对一下算术

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:]) 就是把每个点和下一个点配对的技巧。


SectionSection第 12 节

Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆

🐍 Python Tuples — 8 RulesPython Tuples — 8 नियमPython 元组 —— 8 条法则
1
Commas make tuples — parentheses are optional. 3, 4 and (3, 4) are the same tuple. That is why return x, y works.
Commas tuple बनाते हैं — parentheses वैकल्पिक हैं। 3, 4 और (3, 4) एक ही tuple हैं। इसीलिए return x, y चलता है।
逗号造就元组 —— 括号可有可无。3, 4 和 (3, 4) 是同一个元组。这就是 return x, y 能工作的原因。
2
A one-item tuple needs a trailing comma. (5) is just 5; write (5,). This is the most common tuple bug.
एक item वाले tuple को आख़िरी comma चाहिए। (5) बस 5 है; (5,) लिखें। यह tuple का सबसे आम bug है।
单元素元组需要末尾逗号。(5) 就是 5;要写 (5,)。这是最常见的元组 bug。
3
Tuples cannot be changed. No append, no t[0] = x, no del t[0]. Need any of that? Use a list.
Tuples बदले नहीं जा सकते। न append, न t[0] = x, न del t[0]। इनमें से कुछ चाहिए? List लगाएँ।
元组不能修改。没有 append,不能 t[0] = x,也不能 del t[0]。需要这些?用列表。
4
A tuple is only fully frozen if its items are. In (1, 2, [3, 4]) the list can still change. And beware t[2] += [5]: it raises a TypeError after changing the list.
Tuple तभी पूरी तरह जमा है जब उसके items हों। (1, 2, [3, 4]) में list अब भी बदल सकती है। और t[2] += [5] से सावधान: यह list बदलने के बाद TypeError देता है।
只有当各项都不可变时,元组才是完全冻结的。(1, 2, [3, 4]) 中的列表仍可改变。还要小心 t[2] += [5]:它会在修改列表之后才抛出 TypeError。
5
Tuples are hashable when their items are. That makes them valid dict keys and set members. Lists never are.
Tuples तब hashable हैं जब उनके items हों। इससे वे dict keys और set के सदस्य बन सकते हैं। Lists कभी नहीं।
当各项都可哈希时,元组就可哈希。这让它们能作为 dict 的键和 set 的成员。列表永远不行。
6
Only two methods: count() and index(). Everything else uses built-ins (len, min, max, sum, sorted — which returns a list).
सिर्फ़ दो methods: count() और index()। बाक़ी सब built-ins से (len, min, max, sum, sorted — जो list लौटाता है)।
只有两个方法:count() 和 index()。其余都用内置函数(len、min、max、sum、sorted —— 它返回列表)。
7
Master unpacking. a, b = b, a swaps; first, *rest = t splits (and rest is a list); for name, age in pairs: unpacks each item.
Unpacking में माहिर बनें। a, b = b, a अदला-बदली करता है; first, *rest = t बाँटता है (और rest list है); for name, age in pairs: हर item को unpack करता है।
掌握拆包。a, b = b, a 交换;first, *rest = t 拆分(且 rest 是列表);for name, age in pairs: 拆包每一项。
8
Tuple for a "record", list for a "collection". One GPS point is a tuple; many GPS points are a list of tuples. If each position has its own meaning, use a tuple.
"Record" के लिए tuple, "collection" के लिए list। एक GPS point tuple है; कई GPS points tuples की list हैं। अगर हर जगह का अपना मतलब है, तो tuple लगाएँ।
“记录”用元组,“集合”用列表。一个 GPS 点是元组;许多 GPS 点是元组组成的列表。如果每个位置都有自己的含义,就用元组。
LIVELIVE互动Quick Checkछोटी जाँच小测验

Six questions on tuples. Pick an answer to see why.

Tuples पर छह सवाल। जवाब चुनें और कारण देखें।

关于元组的六道题。选择答案查看解释。

✉️
Key Takeawayमुख्य सीख核心要点

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() 查询,用打包和拆包来交换变量、返回多个值、写出简洁的循环。记录用元组,集合用列表。

🐍 Try Python Yourself

Write, run and visualize Python step by step. No install needed.