The Story That Explains Lists 🗄️Lists समझाने वाली कहानी 🗄️一个解释列表的故事 🗄️
A Python list is that row of lockers. Each slot has a numbered position (an index) and holds one thing. Unlike real lockers, a list slot can hold anything — a number, a string, another list, a function — and the row can grow or shrink whenever you like.
Here is the twist that makes lists so powerful: the lockers do not hold the photos themselves. They hold tickets that say where each photo is kept. That one idea explains how lists behave in memory.
Python की list यही lockers की पंक्ति है। हर slot की एक गिनती वाली जगह (index) है और उसमें एक चीज़ रहती है। असली lockers के उलट, list के slot में कुछ भी रह सकता है — संख्या, string, दूसरी list, function — और पंक्ति जब चाहें बढ़ या घट सकती है।
Lists को इतना ताक़तवर बनाने वाला मोड़ यह है: lockers में photos ख़ुद नहीं रखी होतीं। उनमें पर्चियाँ होती हैं जो बताती हैं कि हर photo कहाँ रखी है। यही एक विचार बताता है कि lists memory में कैसे व्यवहार करती हैं।
Python 的列表就是这排储物柜。每个槽位有一个编号位置(索引),装着一样东西。与真正的柜子不同,列表的槽位可以装任何东西 —— 数字、字符串、另一个列表、函数 —— 而且这一排随时可以变长或变短。
让列表如此强大的关键在于:柜子里放的并不是照片本身,而是写着照片存放位置的票据。这一个想法就能解释列表在内存中的行为。
A list (list) is Python's built-in ordered, mutable sequence. Ordered means each item has a position. Mutable means you can change, add or remove items after the list is made. Lists are the most-used collection in Python.
List (list) Python का built-in क्रमबद्ध, बदलने योग्य sequence है। क्रमबद्ध का मतलब हर item की एक जगह है। बदलने योग्य (mutable) का मतलब list बनने के बाद आप items बदल, जोड़ या हटा सकते हैं। Python में lists सबसे ज़्यादा इस्तेमाल होने वाला collection हैं।
列表(list)是 Python 内置的有序、可变序列。有序是指每一项都有位置;可变是指列表创建后可以修改、添加或删除项。列表是 Python 中最常用的集合类型。
Look for the live boxes: the Memory Model Simulator (Section 03), the Index Lab (04), the Slice Lab (05), the List Method Simulator (06), the Loop Pattern Stepper (07) and the Grid Explorer (08). Type your own lists, press the buttons and watch every slot change. They follow real Python rules — errors included.
Live boxes देखें: Memory Model Simulator (Section 03), Index Lab (04), Slice Lab (05), List Method Simulator (06), Loop Pattern Stepper (07) और Grid Explorer (08)। अपनी lists लिखें, buttons दबाएँ और हर slot को बदलते देखें। ये असली Python के नियम मानते हैं — errors समेत।
留意这些互动框:内存模型模拟器(第 03 节)、索引实验室(04)、切片实验室(05)、列表方法模拟器(06)、循环模式单步器(07)和网格探索器(08)。输入你自己的列表,按下按钮,观察每个槽位的变化。它们遵循真实的 Python 规则 —— 包括报错。
Creating Lists — Four Ways ✍️Lists बनाना — चार तरीक़े ✍️创建列表 —— 四种方式 ✍️
Square brackets are the usual way. list() turns any iterable (a string, a range, a tuple) into a list. * repeats one value, and a comprehension builds a list from a rule.
Square brackets आम तरीक़ा है। list() किसी भी iterable (string, range, tuple) को list बनाता है। * एक मान दोहराता है, और comprehension किसी नियम से list बनाता है।
方括号是最常用的方式。list() 能把任何可迭代对象(字符串、range、元组)变成列表。* 重复一个值,推导式按规则构建列表。
# 1. Literal syntax (most common)
empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [42, "hello", 3.14, True, None]
nested = [[1, 2], [3, 4], [5, 6]]
# 2. The list() constructor — turns any iterable into a list
from_str = list("hello")
from_range = list(range(5))
from_tuple = list((10, 20, 30))
# 3. Repetition — quick lists of the same value
zeros = [0] * 5
# 4. List comprehension — build from a rule
squares = [x ** 2 for x in range(1, 6)]
evens = [x for x in range(20) if x % 2 == 0]
print(empty, len(empty))
print(mixed)
print(from_str, from_range, from_tuple)
print(zeros)
print(squares)
print(evens)
[[0] * 3] * 3 looks like a 3×3 grid, but all three rows are the same list object. Change one and you change all three. Use [[0] * 3 for _ in range(3)] instead — the comprehension makes three separate rows. Here is the real proof:
[[0] * 3] * 3 3×3 grid जैसा दिखता है, पर तीनों rows एक ही list object हैं। एक बदलें तो तीनों बदलती हैं। इसकी जगह [[0] * 3 for _ in range(3)] लगाएँ — comprehension तीन अलग rows बनाता है। असली सबूत यह है:
[[0] * 3] * 3 看起来像 3×3 网格,但三行其实是同一个列表对象。改一行,三行全变。请改用 [[0] * 3 for _ in range(3)] —— 推导式会创建三个独立的行。下面是真实的证明:
bad = [[0] * 3] * 3 # looks like a 3x3 grid…
bad[0][0] = 1
print(bad) # …but every row changed!
print(bad[0] is bad[1]) # all three rows are ONE object
good = [[0] * 3 for _ in range(3)]
good[0][0] = 1
print(good)
print(good[0] is good[1])
How Lists Are Stored in Memory 🧠Lists Memory में कैसे रहती हैं 🧠列表如何存储在内存中 🧠
This is the idea that makes lists click. When you write nums = [10, 20, 30], Python does NOT put 10, 20 and 30 inside the list. The list holds a compact array of references (pointers) to those numbers, which live elsewhere in memory. This design is what lets one list hold different types at once.
यही विचार lists को समझने की कुंजी है। जब आप nums = [10, 20, 30] लिखते हैं, तो Python 10, 20 और 30 को list के अंदर नहीं रखता। List उन संख्याओं के references (pointers) की एक compact array रखती है, और संख्याएँ memory में कहीं और रहती हैं। इसी design से एक list एक साथ अलग-अलग types रख पाती है।
这是理解列表的关键。当你写 nums = [10, 20, 30] 时,Python 并不会把 10、20、30 放进列表里。列表保存的是指向这些数字的引用(指针)组成的紧凑数组,数字本身存放在内存的别处。正是这种设计让一个列表能同时装不同类型。
The Visual Modelचित्र से समझें图解模型
The name points to one list object; each slot points to an int object.
नाम एक list object की ओर है; हर slot एक int object की ओर।
名字指向一个列表对象;每个槽位指向一个 int 对象。
Layer 1 — the variable nums is a sticky note pointing at the list object.
Layer 2 — the list object is a compact array of slots. Each slot holds a reference (a pointer) to a value.
Layer 3 — the values (10, 20, 30) live on their own in the heap. Other lists and variables can point at the same objects.
परत 1 — variable nums list object पर लगी sticky note है।
परत 2 — list object slots की compact array है। हर slot किसी मान का reference (pointer) रखता है।
परत 3 — मान (10, 20, 30) heap में अपनी जगह रहते हैं। दूसरी lists और variables भी उन्हीं objects की ओर इशारा कर सकते हैं।
第 1 层 —— 变量 nums 是贴在列表对象上的便利贴。
第 2 层 —— 列表对象是由槽位组成的紧凑数组,每个槽位保存指向某个值的引用(指针)。
第 3 层 —— 值(10、20、30)独立存放在堆中。其他列表和变量也可以指向同样的对象。
Why This Matters — A Mixed-Type Listयह क्यों अहम है — मिले-जुले Types वाली List为什么重要 —— 混合类型的列表
Every reference has the same size (8 bytes on a 64-bit computer), so the objects behind them can be any type and any size. The sizes below are real sys.getsizeof() values from Python 3.13.16. (A plain C array or a Java int[] holds only one type. Java gets mixed lists the same way Python does — with an array of references, Object[].)
हर reference का आकार एक जैसा है (64-bit computer पर 8 bytes), इसलिए उनके पीछे के objects किसी भी type और किसी भी आकार के हो सकते हैं। नीचे के आकार Python 3.13.16 के असली sys.getsizeof() मान हैं। (साधारण C array या Java का int[] सिर्फ़ एक type रखता है। Java में मिली-जुली lists Python की तरह ही बनती हैं — references की array, Object[] से।)
每个引用大小相同(64 位电脑上是 8 字节),所以引用背后的对象可以是任意类型、任意大小。下面的大小是 Python 3.13.16 中真实的 sys.getsizeof() 值。(普通的 C 数组或 Java 的 int[] 只能装一种类型。Java 实现混合列表的方式和 Python 一样 —— 用引用数组 Object[]。)
Sizes are real sys.getsizeof() values in bytes.
आकार bytes में असली sys.getsizeof() मान हैं।
大小是以字节为单位的真实 sys.getsizeof() 值。
Consequences of the Reference ModelReference Model के नतीजे引用模型带来的结果
value = 1000 # an int outside the small-int cache
data = [value, value, value]
print(data[0] is data[1], data[0] is value) # all slots point to ONE object
a = [1, 2, 3]
b = a # NOT a copy — a second name for the same list
b.append(4)
print(a, a is b)
c = a.copy() # a new list (same items inside)
c.append(5)
print(a, c, a is c, a == a[:])
See the Spare Room Growख़ाली जगह को बढ़ते देखें观察预留空间的增长
sys.getsizeof() shows the size of the list object itself (not the items). Watch it jump only now and then while we append 20 items one by one:
sys.getsizeof() list object का अपना आकार दिखाता है (items का नहीं)। जब हम एक-एक करके 20 items जोड़ते हैं, तो देखिए यह सिर्फ़ कभी-कभी उछलता है:
sys.getsizeof() 显示的是列表对象本身的大小(不含各项)。我们逐个 append 20 项,看看它只是偶尔跳一下:
import sys
print(sys.getsizeof([10, 20, 30]), "bytes for the list object itself")
print(sys.getsizeof(42), sys.getsizeof("hi"), sys.getsizeof(3.14), sys.getsizeof(True))
nums = []
last = sys.getsizeof(nums)
for i in range(20):
nums.append(i)
size = sys.getsizeof(nums)
if size != last: # the hidden array just grew
slots = (size - sys.getsizeof([])) // 8
print(f"len {len(nums):>2}: room for {slots} references")
last = size
The literal [10, 20, 30] takes 88 bytes: a fixed header plus room for 4 references. When we append item 1, Python reserves room for 4. It grows again only at items 5, 9 and 17. Most appends just fill a spare slot, which is why append() is fast. (The exact growth steps are a CPython detail and can change between versions.)
Literal [10, 20, 30] 88 bytes लेता है: एक स्थिर header और 4 references की जगह। Item 1 जोड़ते ही Python 4 की जगह रख लेता है। यह फिर सिर्फ़ items 5, 9 और 17 पर बढ़ता है। ज़्यादातर appends बस एक ख़ाली slot भरते हैं, इसीलिए append() तेज़ है। (बढ़ने के सटीक क़दम CPython की अंदरूनी बात हैं और versions के बीच बदल सकते हैं।)
字面量 [10, 20, 30] 占 88 字节:固定的头部加上 4 个引用的空间。append 第 1 项时,Python 预留了 4 个位置;之后只在第 5、9、17 项时才再次增长。大多数 append 只是填一个空槽位,所以 append() 很快。(具体的增长步骤是 CPython 的实现细节,不同版本可能不同。)
Indexing — Reaching One Item 🎯Indexing — एक Item तक पहुँचना 🎯索引 —— 取到单个项 🎯
A list is ordered, so every item has a numbered position. Python counts from zero and also accepts negative indexes, which count from the end. Unlike a string, a list lets you write to a slot as well as read it.
List क्रमबद्ध है, इसलिए हर item की एक गिनती वाली जगह है। Python शून्य से गिनता है और negative indexes भी लेता है, जो अंत से गिनते हैं। String के उलट, list में आप slot को पढ़ने के साथ लिख भी सकते हैं।
列表是有序的,所以每一项都有编号位置。Python 从零开始数,也接受从末尾数的负索引。与字符串不同,列表的槽位既能读也能写。
colors = ["red", "green", "blue", "yellow", "purple"]
print(colors[0], colors[2], colors[4])
print(colors[-1], colors[-2], colors[-5])
colors[1] = "forest green" # lists are mutable: replace one slot
print(colors)
print(len(colors), colors[len(colors) - 1], colors[-1])
try:
colors[10]
except IndexError as err:
print("IndexError:", err)
try:
colors[10] = "pink"
except IndexError as err:
print("IndexError:", err)
Note the two different messages: reading a missing index says list index out of range, while writing says list assignment index out of range. To add a new item, use append() or insert().
दो अलग संदेश देखें: ग़ायब index पढ़ने पर list index out of range आता है, जबकि लिखने पर list assignment index out of range। नया item जोड़ने के लिए append() या insert() लगाएँ।
注意两条不同的报错:读取不存在的索引报 list index out of range,写入则报 list assignment index out of range。要添加新项,用 append() 或 insert()。
Slicing — Taking Sub-Lists ✂️Slicing — छोटी Lists निकालना ✂️切片 —— 取出子列表 ✂️
Slicing copies part of a list into a new list. The syntax is the same as for strings: lst[start:stop:step], and all three parts are optional. Unlike indexing, slicing never crashes on out-of-range numbers — it returns what is there. Lists add one extra power: slice assignment, which changes the original list.
Slicing list का एक हिस्सा नई list में copy करती है। Syntax strings जैसा है: lst[start:stop:step], और तीनों हिस्से वैकल्पिक हैं। Indexing के उलट, slicing सीमा से बाहर के अंकों पर कभी नहीं रुकती — जो है वही लौटाती है। Lists में एक और ताक़त है: slice assignment, जो असली list बदलता है।
切片把列表的一部分复制到一个新列表中。语法与字符串相同:lst[start:stop:step],三部分都可省略。与索引不同,切片遇到越界数字永不报错,有什么就返回什么。列表还多一项本领:切片赋值,它会修改原列表。
nums = [10, 20, 30, 40, 50, 60, 70, 80]
print(nums[2:5], nums[:3], nums[5:])
print(nums[-3:], nums[:-2], nums[-5:-2])
print(nums[::2], nums[1::2])
print(nums[::-1])
print(nums[100:200], nums[5:100]) # slicing never crashes
copy = nums[:]
print(copy == nums, copy is nums) # a new list
data = [1, 2, 3, 4, 5]
data[1:4] = [99, 99] # replace 3 items with 2
print(data)
data[1:1] = [7, 8] # insert without removing
print(data)
data[2:4] = [] # delete a range
print(data)
Slicing Cheat SheetSlicing Cheat Sheet切片速查表
| PatternPattern写法 | Meaningमतलब含义 | Example on [10, 20, 30, 40, 50][10, 20, 30, 40, 50] पर उदाहरण在 [10, 20, 30, 40, 50] 上的示例 |
|---|---|---|
| lst[a:b] | Indexes a to b-1Index a से b-1 तक索引 a 到 b-1 | lst[1:4] → [20, 30, 40] |
| lst[:n] | First n itemsपहले n items前 n 项 | lst[:3] → [10, 20, 30] |
| lst[n:] | From index n to the endIndex n से अंत तक从索引 n 到末尾 | lst[3:] → [40, 50] |
| lst[-n:] | Last n itemsआख़िरी n items最后 n 项 | lst[-2:] → [40, 50] |
| lst[:-n] | All except the last nआख़िरी n छोड़कर सब除最后 n 项外的全部 | lst[:-2] → [10, 20, 30] |
| lst[::-1] | Reversed copyउल्टी copy反转的副本 | lst[::-1] → [50, 40, 30, 20, 10] |
| lst[::2] | Every 2nd itemहर दूसरा item每隔一项 | lst[::2] → [10, 30, 50] |
| lst[:] | Shallow copyShallow copy浅拷贝 | lst[:] → [10, 20, 30, 40, 50] |
With step 1, slice assignment can change the length: [1:4] = [99, 99] swaps 3 items for 2, [1:1] = [7, 8] inserts, and = [] deletes. With any other step (an extended slice), the new list must have exactly as many items as the slots — try [::2] = [0] to see the ValueError.
Step 1 हो तो slice assignment लंबाई बदल सकता है: [1:4] = [99, 99] 3 items की जगह 2 रखता है, [1:1] = [7, 8] डालता है, और = [] मिटाता है। किसी और step (extended slice) पर नई list में slots जितने ही items ठीक-ठीक होने चाहिए — ValueError देखने के लिए [::2] = [0] आज़माएँ।
步长为 1 时,切片赋值可以改变长度:[1:4] = [99, 99] 用 2 项换掉 3 项,[1:1] = [7, 8] 是插入,= [] 是删除。其他步长(扩展切片)时,新列表的项数必须与槽位数完全相同 —— 试试 [::2] = [0] 看看 ValueError。
List Methods — The Essential Toolkit 🧰List Methods — ज़रूरी औज़ार 🧰列表方法 —— 必备工具箱 🧰
Lists have exactly 11 public methods. They fall into three groups: mutators change the list in place and (except pop) return None; queries return information; and the builder copy() returns a new list. Built-in functions such as sorted(), len() and sum() work alongside them.
Lists में ठीक 11 public methods हैं। ये तीन समूहों में बँटते हैं: mutators list को अपनी जगह बदलते हैं और (pop को छोड़कर) None लौटाते हैं; queries जानकारी लौटाते हैं; और builder copy() नई list लौटाता है। sorted(), len() और sum() जैसे built-in functions इनके साथ काम करते हैं।
列表恰好有 11 个公开方法,分为三组:修改器原地修改列表,并(除 pop 外)返回 None;查询返回信息;构建器 copy() 返回新列表。sorted()、len()、sum() 等内置函数与它们配合使用。
Mutators — Change the List in PlaceMutators — List को अपनी जगह बदलना修改器 —— 原地修改列表
tasks = ["code", "test"]
tasks.append("deploy")
tasks.extend(["review", "ship"])
print(tasks)
a = [1, 2]
a.append([3, 4]) # ONE item (a list)
b = [1, 2]
b.extend([3, 4]) # each item
print(a, b)
c = [1, 2]
c.extend("hi") # a string is iterable: one item per character
print(c)
letters = ["a", "c", "d"]
letters.insert(1, "b")
print(letters)
nums = [1, 2, 3, 2, 1]
nums.remove(2) # removes the FIRST 2 only
print(nums)
try:
nums.remove(99)
except ValueError as err:
print("ValueError:", err)
stack = [10, 20, 30, 40]
last = stack.pop()
first = stack.pop(0)
print(last, first, stack)
data = [3, 1, 4, 1, 5, 9, 2, 6]
data.sort()
print(data)
data.sort(reverse=True)
print(data)
words = ["apple", "kiwi", "strawberry", "fig"]
words.sort(key=len) # by length: 3, 4, 5, 10 letters
print(words)
seq = [1, 2, 3, 4]
print(seq.reverse()) # mutators return None!
print(seq)
seq.clear()
print(seq)
print(seq.reverse()) printed None above. So nums = nums.sort() quietly turns nums into None (see the last example below). Call a mutator on its own line, or use a function that returns a new object: sorted(nums) gives a new list and reversed(nums) gives an iterator.
ऊपर print(seq.reverse()) ने None छापा। इसलिए nums = nums.sort() चुपचाप nums को None बना देता है (नीचे का आख़िरी उदाहरण देखें)। Mutator को अलग line में call करें, या नया object लौटाने वाला function लगाएँ: sorted(nums) नई list देता है और reversed(nums) एक iterator।
上面 print(seq.reverse()) 打印出了 None。所以 nums = nums.sort() 会悄悄把 nums 变成 None(见下面最后一个例子)。修改器要单独一行调用,或者使用返回新对象的函数:sorted(nums) 返回新列表,reversed(nums) 返回迭代器。
Queries — Return InformationQueries — जानकारी लौटाना查询 —— 返回信息
votes = ["yes", "no", "yes", "yes", "no"]
print(votes.count("yes"), votes.count("maybe"))
print(votes.index("no"))
try:
votes.index("maybe")
except ValueError as err:
print("ValueError:", err)
if "no" in votes:
print(f"Found at {votes.index('no')}")
scores = [88, 75, 92, 60, 83]
print(len(scores), min(scores), max(scores), sum(scores))
print(sum(scores) / len(scores))
print([1, 1.0, True].count(1)) # 1 == 1.0 == True in Python
The last line surprises many people: [1, 1.0, True].count(1) is 3, because 1 == 1.0 == True in Python. count(), index(), remove() and in all compare with ==.
आख़िरी line कई लोगों को चौंकाती है: [1, 1.0, True].count(1) 3 है, क्योंकि Python में 1 == 1.0 == True। count(), index(), remove() और in सब == से तुलना करते हैं।
最后一行让很多人意外:[1, 1.0, True].count(1) 等于 3,因为在 Python 中 1 == 1.0 == True。count()、index()、remove() 和 in 都用 == 比较。
Builders — Return Something NewBuilders — कुछ नया लौटाना构建器 —— 返回新的东西
original = [1, 2, 3]
duplicate = original.copy() # same as original[:] or list(original)
duplicate.append(4)
print(original, duplicate)
data = [3, 1, 2]
print(sorted(data), data) # sorted() returns a NEW list
r = reversed(data) # reversed() returns an iterator, not a list
print(type(r).__name__, list(r))
nums = [3, 1, 2]
nums = nums.sort() # the classic trap
print(nums)
Complete Methods Referenceपूरी Methods सूची完整方法速查
| Groupसमूह类别 | MethodMethod方法 | What it doesक्या करता है作用 | Returnsलौटाता है返回 |
|---|---|---|---|
| MutatorsMutators修改器 | .append(x) | Add one item to the endअंत में एक item जोड़ें在末尾添加一项 | None |
| .extend(iterable) | Add each item of an iterableIterable का हर item जोड़ें添加可迭代对象的每一项 | None | |
| .insert(i, x) | Insert x before index iIndex i से पहले x डालें在索引 i 前插入 x | None | |
| .remove(x) | Delete the first item equal to xx के बराबर पहला item मिटाएँ删除第一个等于 x 的项 | None / ValueError | |
| .pop([i]) | Remove and return the item at i (default -1)i (default -1) का item हटाकर लौटाएँ删除并返回索引 i 处的项(默认 -1) | the itemवह item该项 | |
| .sort(key=, reverse=) | Sort in place (stable)अपनी जगह sort (stable)原地排序(稳定) | None | |
| .reverse() | Reverse in placeअपनी जगह उलटें原地反转 | None | |
| .clear() | Remove every itemहर item हटाएँ删除所有项 | None | |
| QueriesQueries查询 | .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 | |
| BuilderBuilder构建器 | .copy() | Shallow copy (same as lst[:])Shallow copy (lst[:] जैसा)浅拷贝(同 lst[:]) | new listनई list新列表 |
| Not methodsMethods नहीं不是方法 | del lst[i] / del lst[a:b] | Statement: delete by index or sliceStatement: index या slice से मिटाएँ语句:按索引或切片删除 | — |
| sorted(lst) | Function: a new sorted listFunction: नई sorted list函数:新的已排序列表 | new listनई list新列表 | |
| reversed(lst) | Function: an iterator, backwardsFunction: उल्टा चलने वाला iterator函数:反向迭代器 | iterator | |
| len / min / max / sum | Functions: size and totalsFunctions: आकार और जोड़函数:长度与汇总 | a valueएक मान一个值 |
The for Loop — Walking Through Lists 🔄for Loop — Lists में चलना 🔄for 循环 —— 遍历列表 🔄
The for loop walks through a list one item at a time. Python's for is a for-each loop: it hands you the items directly, not index numbers as in C. That is why it reads almost like English.
for loop list में एक-एक item करके चलता है। Python का for एक for-each loop है: यह सीधे items देता है, C की तरह index अंक नहीं। इसीलिए यह लगभग अंग्रेज़ी जैसा पढ़ा जाता है।
for 循环逐项遍历列表。Python 的 for 是 for-each 循环:它直接交给你各项,而不是像 C 那样给索引号。所以读起来几乎像英语。
Patterns 1 and 2 — Values, and Values With an IndexPatterns 1 और 2 — मान, और Index के साथ मान模式 1 和 2 —— 取值,以及带索引取值
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}")
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
for num, fruit in enumerate(fruits, start=1):
print(f"Item #{num}: {fruit}")
| CodeCode代码 |
|---|
| for i in range(len(fruits)): |
| print(i, fruits[i]) |
| Needs len() and indexing.len() और indexing चाहिए।需要 len() 和索引。 |
| CodeCode代码 |
|---|
| for i, fruit in enumerate(fruits): |
| print(i, fruit) |
| Clean, and says what it means.साफ़, और मतलब साफ़ बताता है।简洁,一看就懂。 |
Pattern 3 — Two Lists Side by Side With zip()Pattern 3 — zip() से दो Lists साथ-साथ模式 3 —— 用 zip() 并排遍历两个列表
names = ["Asha", "Ravi", "Meena"]
scores = [92, 85, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
short = ["x", "y"]
long = [1, 2, 3, 4]
for a, b in zip(short, long): # stops at the shortest list
print(a, b)
try: # Python 3.10+: ask zip to check the lengths
list(zip(short, long, strict=True))
except ValueError as err:
print("ValueError:", err)
zip() stops at the shortest list and ignores the rest with no warning — items 3 and 4 above were never used. From Python 3.10, zip(..., strict=True) raises a ValueError instead, which catches lists that should have the same length but do not.
zip() सबसे छोटी list पर रुक जाता है और बाक़ी को बिना चेतावनी छोड़ देता है — ऊपर items 3 और 4 कभी इस्तेमाल नहीं हुए। Python 3.10 से zip(..., strict=True) इसकी जगह ValueError देता है, जिससे वे lists पकड़ी जाती हैं जिनकी लंबाई बराबर होनी चाहिए थी पर नहीं है।
zip() 在最短的列表处停止,其余部分被直接忽略,没有任何警告 —— 上面的 3 和 4 从未被使用。从 Python 3.10 起,zip(..., strict=True) 会改为抛出 ValueError,帮你发现本应等长却不等长的列表。
Pattern 4 — Building a New ListPattern 4 — नई List बनाना模式 4 —— 构建新列表
numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
squares.append(n * n)
print(squares)
squares = [n * n for n in numbers]
print(squares)
even_squares = [n * n for n in numbers if n % 2 == 0]
print(even_squares)
Pattern 5 — break, continue and elsePattern 5 — break, continue और else模式 5 —— break、continue 与 else
numbers = [1, 3, 5, 8, 10, 12]
for n in numbers:
if n % 2 == 0:
print(f"First even: {n}")
break
for n in numbers:
if n % 2 != 0:
continue # skip odd numbers
print(n, end=" ")
print()
for n in numbers:
if n == 99:
print("Found 99!")
break
else:
print("99 not found in the list") # runs only when no break happened
Removing items from a list while you loop over it makes the loop skip items. Below, -2 survives because after -1 is removed, -2 slides into the slot the loop has already passed. Build a new list with a comprehension, or loop over a copy: for n in nums[:]:. Try the remove while looping tab above to watch it happen.
किसी list में loop करते हुए items हटाने से loop items छोड़ देता है। नीचे -2 बच जाता है, क्योंकि -1 हटने के बाद -2 उस slot में खिसक जाता है जिसे loop पार कर चुका है। Comprehension से नई list बनाएँ, या copy पर loop करें: for n in nums[:]:। इसे होते देखने के लिए ऊपर loop में हटाना tab आज़माएँ।
在遍历列表的同时删除其中的项,会让循环跳过某些项。下面的 -2 幸存了下来,因为 -1 被删除后,-2 滑进了循环已经走过的槽位。请用推导式构建新列表,或者遍历副本:for n in nums[:]:。试试上面的边遍历边删除标签,亲眼看看。
nums = [-1, -2, 3, -4, 5]
for n in nums:
if n < 0:
nums.remove(n) # changing the list we are looping over
print(nums) # -2 survived: it was skipped!
nums = [-1, -2, 3, -4, 5]
nums = [n for n in nums if n >= 0] # safe: build a new list
print(nums)
Nested Lists — Lists of Lists 🔢Nested Lists — Lists की Lists 🔢嵌套列表 —— 列表的列表 🔢
A list can hold any type, so it can hold other lists. This is how you build grids, matrices and tables in Python. Read grid[r][c] in two steps: grid[r] picks the row list, then [c] picks the item in that row.
List कोई भी type रख सकती है, इसलिए वह दूसरी lists भी रख सकती है। Python में grids, matrices और tables ऐसे ही बनते हैं। grid[r][c] को दो क़दमों में पढ़ें: grid[r] row वाली list चुनता है, फिर [c] उस row का item।
列表能装任何类型,所以也能装其他列表。Python 中的网格、矩阵和表格就是这样构建的。把 grid[r][c] 分两步读:grid[r] 取出这一行的列表,然后 [c] 取出该行中的项。
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(grid[0][0], grid[2][2], grid[1][2])
grid[1][1] = 0
print(grid)
print(len(grid), len(grid[0])) # rows, columns
for row in grid:
for cell in row:
print(cell, end=" ")
print()
for r, row in enumerate(grid):
for c, cell in enumerate(row):
if cell == 0:
print(f"Zero at ({r},{c})")
table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
for row in table:
print(row)
Complete Practice Program — Inventory Manager 🛒पूरा अभ्यास Program — Inventory Manager 🛒完整练习程序 —— 库存管理器 🛒
This program uses every idea from the lesson: creating lists, zip(), len/min/max/sum, indexing and slicing, mutators, a comprehension and for-else. The output below is a real run.
यह program lesson का हर विचार इस्तेमाल करता है: lists बनाना, zip(), len/min/max/sum, indexing और slicing, mutators, comprehension और for-else। नीचे का output असली run है।
这个程序用到了本课的所有概念:创建列表、zip()、len/min/max/sum、索引与切片、修改器、推导式和 for-else。下面的输出是真实运行结果。
# inventory.py — every list concept in one working program
def main():
# CREATE — parallel lists: item i has price i and quantity i
inventory = ["apple", "bread", "milk", "eggs", "cheese"]
prices = [1.20, 3.50, 2.80, 4.00, 5.50]
quantity = [12, 5, 8, 24, 3]
line = "─" * 44
print(f"{line}\n INVENTORY REPORT\n{line}")
# LOOP WITH zip() — walk the three lists together
print(f" {'ITEM':<10}{'QTY':>6}{'PRICE $':>12}{'TOTAL $':>12}")
grand_total = 0
for item, qty, price in zip(inventory, quantity, prices):
total = qty * price
grand_total += total
print(f" {item:<10}{qty:>6}{price:>12.2f}{total:>12.2f}")
print(f"{line}\n Grand total: ${grand_total:.2f}")
# QUERIES — len, min, max, sum
print(f"\n Items in stock: {len(inventory)}")
print(f" Cheapest item: {inventory[prices.index(min(prices))]} (${min(prices):.2f})")
print(f" Priciest item: {inventory[prices.index(max(prices))]} (${max(prices):.2f})")
print(f" Total units: {sum(quantity)}")
# LIST COMPREHENSION — do this BEFORE changing the order of inventory,
# while item i still matches price i
on_sale = [item for item, price in zip(inventory, prices) if price < 3]
print(f" Items under $3: {on_sale}")
# INDEXING & SLICING
print(f"\n First item: {inventory[0]}")
print(f" Last item: {inventory[-1]}")
print(f" Top 3: {inventory[:3]}")
print(f" Reversed: {inventory[::-1]}")
# MUTATORS — append, insert, remove, sort
inventory.append("yogurt")
inventory.insert(0, "almonds")
inventory.remove("eggs")
inventory.sort()
print(f"\n Updated (sorted): {inventory}")
# FOR-ELSE — search pattern
target = "chocolate"
for item in inventory:
if item == target:
print(f" Found {target}!")
break
else:
print(f" {target} is out of stock")
if __name__ == "__main__":
main()
inventory and prices are parallel lists: item i matches price i. After insert, remove and sort, that link is broken — "almonds" would be paired with apple's price. That is why the "under $3" list is built before the list is changed. (Later you will meet dictionaries, which keep each name and price together.)
inventory और prices समानांतर lists हैं: item i का मेल price i से है। insert, remove और sort के बाद यह जोड़ टूट जाता है — "almonds" को apple का price मिल जाता। इसीलिए "under $3" वाली list, list बदलने से पहले बनाई गई है। (आगे आप dictionaries सीखेंगे, जो हर नाम और price को साथ रखती हैं।)
inventory 和 prices 是平行列表:第 i 项对应第 i 个价格。经过 insert、remove 和 sort 之后,这种对应就被打乱了 —— "almonds" 会配上 apple 的价格。所以“低于 $3”的列表要在修改列表之前构建。(以后你会学到字典,它能把每个名字和价格放在一起。)
Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆
Six questions on lists. Pick an answer to see why.
Lists पर छह सवाल। जवाब चुनें और कारण देखें।
关于列表的六道题。选择答案查看解释。
A list is an ordered, mutable row of references. Index it with lst[i], slice it with lst[a:b:c] (a new list) or slice-assign to change it in place. Mutators change the list and return None; copy(), sorted() and slices give you new lists. Loop with enumerate() and zip(), never remove items while looping, and remember that b = a and [[0]*3]*3 share objects instead of copying them.
List references की क्रमबद्ध, बदलने योग्य पंक्ति है। lst[i] से index करें, lst[a:b:c] से slice करें (नई list) या अपनी जगह बदलने के लिए slice-assign करें। Mutators list बदलते हैं और None लौटाते हैं; copy(), sorted() और slices नई lists देते हैं। enumerate() और zip() से loop करें, loop करते हुए items कभी न हटाएँ, और याद रखें कि b = a और [[0]*3]*3 objects की copy नहीं बनाते, उन्हें साझा करते हैं।
列表是由引用组成的有序、可变的一排。用 lst[i] 索引,用 lst[a:b:c] 切片(得到新列表),或用切片赋值原地修改。修改器改变列表并返回 None;copy()、sorted() 和切片会给你新列表。用 enumerate() 和 zip() 遍历,绝不边遍历边删除,并记住 b = a 和 [[0]*3]*3 是共享对象,而不是复制。