BASIC Python (Beginner Level) 📂 Basic Python Programming · 8 of 15 229 min read

Python Lists — Memory Model, Indexing, Slicing

Master Python lists from the ground up. This tutorial explains how lists are stored in memory as arrays of references (with animated diagrams), positive and negative indexing, complete slicing syntax with start/stop/step, all 11 built-in list methods split into mutators/queries/builders, five different for-loop patterns including enumerate, zip, break/continue/else, list comprehensions, nested lists for 2D grids, and a full inventory-manager practice program.

🌐
SectionSection第 01 节

The Story That Explains Lists 🗄️Lists समझाने वाली कहानी 🗄️一个解释列表的故事 🗄️

A Row of Numbered Lockersनंबर वाले Lockers की पंक्ति一排编了号的储物柜
Picture a row of school lockers, each with a number painted on the front: 0, 1, 2, 3, 4. Inside each locker is a photo. You can walk up to locker 3 and see whose photo is inside. You can swap the photo for someone else's. You can add a new locker at the end. You can even take lockers 1 to 3 and photocopy them into a new row.

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.
स्कूल के lockers की एक पंक्ति सोचिए, हर एक पर नंबर लिखा है: 0, 1, 2, 3, 4। हर locker में एक photo है। आप locker 3 तक जाकर देख सकते हैं कि अंदर किसकी photo है। आप photo को किसी और की photo से बदल सकते हैं। अंत में नया locker जोड़ सकते हैं। Lockers 1 से 3 की photocopy करके नई पंक्ति भी बना सकते हैं।

Python की list यही lockers की पंक्ति है। हर slot की एक गिनती वाली जगह (index) है और उसमें एक चीज़ रहती है। असली lockers के उलट, list के slot में कुछ भी रह सकता है — संख्या, string, दूसरी list, function — और पंक्ति जब चाहें बढ़ या घट सकती है।

Lists को इतना ताक़तवर बनाने वाला मोड़ यह है: lockers में photos ख़ुद नहीं रखी होतीं। उनमें पर्चियाँ होती हैं जो बताती हैं कि हर photo कहाँ रखी है। यही एक विचार बताता है कि lists memory में कैसे व्यवहार करती हैं।
想象一排学校储物柜,每个柜门上都写着编号:0、1、2、3、4。每个柜子里有一张照片。你可以走到 3 号柜看看里面是谁的照片,可以把照片换成别人的,可以在末尾加一个新柜子,甚至可以把 1 到 3 号柜复印成新的一排。

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 中最常用的集合类型。

📑
Orderedक्रमबद्ध有序
position mattersजगह मायने रखती है位置很重要
Items keep the order you put them in. The item at index 0 stays there until you move it. That is what makes indexing and slicing work.
Items उसी क्रम में रहते हैं जिसमें आपने रखे। Index 0 वाला item तब तक वहीं रहता है जब तक आप उसे न हिलाएँ। इसी से indexing और slicing काम करते हैं।
各项保持你放入的顺序。索引 0 的项会一直在那里,直到你移动它。索引和切片正是依赖这一点。
🔧
MutableMutable可变
change in placeअपनी जगह बदलाव原地修改
Unlike strings and tuples, a list can change without making a new object. Append, insert, remove or replace items — all in the same list.
Strings और tuples के उलट, list नया object बनाए बिना बदल सकती है। Items जोड़ें, डालें, हटाएँ या बदलें — सब उसी list में।
与字符串和元组不同,列表无需创建新对象就能修改。添加、插入、删除或替换项 —— 都在同一个列表里。
🎗
Any Typeकोई भी Type任意类型
mix freelyखुलकर मिलाएँ自由混合
One list can hold ints, strings, floats, booleans, other lists, functions — anything. The items do not need to be the same type.
एक list में ints, strings, floats, booleans, दूसरी lists, functions — कुछ भी हो सकता है। Items का एक ही type होना ज़रूरी नहीं।
一个列表可以装 int、字符串、浮点数、布尔值、其他列表、函数 —— 任何东西。各项不必是同一类型。
▶️
This Tutorial Has Six Simulatorsइस Tutorial में छह Simulators हैं本教程有六个模拟器

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 规则 —— 包括报错。


SectionSection第 02 节

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)
OUTPUT
[] 0 [42, 'hello', 3.14, True, None] ['h', 'e', 'l', 'l', 'o'] [0, 1, 2, 3, 4] [10, 20, 30] [0, 0, 0, 0, 0] [1, 4, 9, 16, 25] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
⚠️
The Repetition Trap With Nested ListsNested Lists में दोहराव का जाल嵌套列表的重复陷阱

[[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])
OUTPUT
[[1, 0, 0], [1, 0, 0], [1, 0, 0]] True [[1, 0, 0], [0, 0, 0], [0, 0, 0]] False

SectionSection第 03 节

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

🧠 nums = [10, 20, 30] in memory🧠 Memory में nums = [10, 20, 30]🧠 内存中的 nums = [10, 20, 30]
How a list is stored in memorynumsvariablevariable变量LIST OBJECT — a compact array of referencesLIST OBJECT — references की compact array列表对象 —— 引用组成的紧凑数组[0]ref[1]ref[2]reflen 3 · room for 4 references (spare slot for growth)len 3 · 4 references की जगह (बढ़ने के लिए ख़ाली slot)len 3 · 可容纳 4 个引用(预留一个空位用于增长)HEAP:HEAP:堆:the real objectsअसली objects真正的对象live hereयहाँ रहते हैं住在这里10int20int30int

The name points to one list object; each slot points to an int object.

नाम एक list object की ओर है; हर slot एक int object की ओर।

名字指向一个列表对象;每个槽位指向一个 int 对象。

💡
Three Layers to Rememberयाद रखने लायक़ तीन परतें要记住的三层

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[]。)

🎨 One list, four types🎨 एक list, चार types🎨 一个列表,四种类型
A mixed-type list in memorymixed = [42, "hi", 3.14, True][0] ref42int · 28 B[1] ref"hi"str · 43 B[2] ref3.14float · 24 B[3] refTruebool · 28 BSlots are all the same size · objects are not · everything fitsSlots एक आकार के · objects नहीं · सब समा जाता है槽位大小相同 · 对象各不相同 · 全都装得下

Sizes are real sys.getsizeof() values in bytes.

आकार bytes में असली sys.getsizeof() मान हैं।

大小是以字节为单位的真实 sys.getsizeof() 值。

Consequences of the Reference ModelReference Model के नतीजे引用模型带来的结果

📈
O(1) IndexingO(1) IndexingO(1) 索引
constant-time accessस्थिर समय में पहुँच常数时间访问
Slots are the same size and sit side by side, so Python finds lst[i] with one calculation. 10 items or 10 million — reading any index takes the same time.
Slots एक आकार के हैं और साथ-साथ रखे हैं, इसलिए Python एक गणना से lst[i] ढूँढ लेता है। 10 items हों या 1 करोड़ — कोई भी index पढ़ने में उतना ही समय लगता है।
槽位大小相同且紧挨着,所以 Python 一次计算就能找到 lst[i]。10 项还是 1000 万项,读取任意索引都一样快。
🔁
Shared Objectsसाझा Objects共享对象
cheap duplicatesसस्ते duplicates重复很廉价
Putting the same object in a list three times does not copy it. All three slots point to one object, as the next example proves with is.
एक ही object को list में तीन बार रखने से उसकी copy नहीं बनती। तीनों slots एक ही object की ओर इशारा करते हैं, जैसा अगला उदाहरण is से साबित करता है।
把同一个对象往列表里放三次并不会复制它。三个槽位都指向同一个对象,下一个例子会用 is 证明这一点。
🛠️
Growable — With Spare Roomबढ़ने योग्य — ख़ाली जगह के साथ可增长 —— 预留空间
amortised O(1) appendऔसतन O(1) append均摊 O(1) 的 append
A list keeps extra empty slots. When they run out, Python makes a bigger array and copies the references over. So append() is O(1) on average and only sometimes O(n).
List कुछ अतिरिक्त ख़ाली slots रखती है। जब वे ख़त्म होते हैं, Python बड़ी array बनाकर references उसमें copy करता है। इसलिए append() औसतन O(1) है और कभी-कभार ही O(n)।
列表会保留额外的空槽位。用完时,Python 会建一个更大的数组并把引用复制过去。所以 append() 平均是 O(1),只是偶尔 O(n)。
⚠️
Shared List = Shared Troubleसाझा List = साझा मुसीबत共享列表 = 共享麻烦
the aliasing gotchaaliasing का जाल别名陷阱
A variable holds a reference, so b = a makes both names point at the same list. A change through b shows up in a. Use a.copy() or a[:] for a real copy.
Variable एक reference रखता है, इसलिए b = a से दोनों नाम एक ही list की ओर हो जाते हैं। b से किया बदलाव a में भी दिखता है। असली copy के लिए a.copy() या a[:] लगाएँ।
变量保存的是引用,所以 b = a 让两个名字指向同一个列表。通过 b 的修改会在 a 上体现。要真正复制,用 a.copy() 或 a[:]。
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[:])
OUTPUT
True True [1, 2, 3, 4] True [1, 2, 3, 4] [1, 2, 3, 4, 5] False True

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
OUTPUT
88 bytes for the list object itself 28 43 24 28 len 1: room for 4 references len 5: room for 8 references len 9: room for 16 references len 17: room for 24 references
📦
What the Numbers Meanअंकों का मतलब这些数字的含义

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 的实现细节,不同版本可能不同。)

🧠 Memory Model SimulatorMemory Model Simulator内存模型模拟器Names → list objects → heap objects. Run one line at a time.नाम → list objects → heap objects। एक-एक line चलाएँ।名字 → 列表对象 → 堆对象。逐行运行。

SectionSection第 04 节

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 从零开始数,也接受从末尾数的负索引。与字符串不同,列表的槽位既能读也能写。

🎯 Index Lab — lst[i] and lst[i] = xIndex Lab — lst[i] और lst[i] = x索引实验室 —— lst[i] 与 lst[i] = xRead or change one slot. Click any box.एक slot पढ़ें या बदलें। किसी box पर click करें।读取或修改一个槽位。可点击任意方块。
Quick:जल्दी:快捷:
top = positive index · bottom = negative indexऊपर = positive index · नीचे = negative index上方 = 正索引 · 下方 = 负索引
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)
OUTPUT
red blue purple purple yellow red ['red', 'forest green', 'blue', 'yellow', 'purple'] 5 purple purple IndexError: list index out of range IndexError: list assignment index out of range

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()。


SectionSection第 05 节

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],三部分都可省略。与索引不同,切片遇到越界数字永不报错,有什么就返回什么。列表还多一项本领:切片赋值,它会修改原列表。

Slice SyntaxSlice Syntax切片语法
lst[start : stop : step]
start = included (default 0) · stop = NOT included (default len) · step = jump size (default 1)
start = शामिल (default 0) · stop = शामिल नहीं (default len) · step = छलांग (default 1)
start = 包含(默认 0)· stop = 不包含(默认 len)· step = 步长(默认 1)
Returns a CopyCopy लौटाती है返回副本
new list — original untouchedनई list — असली अछूती新列表 —— 原列表不变
Reading a slice always builds a fresh list. Handy: lst[:] is the shortest way to make a shallow copy.
Slice पढ़ना हमेशा नई list बनाता है। काम की बात: shallow copy बनाने का सबसे छोटा तरीक़ा lst[:] है।
读取切片总会生成一个新列表。小技巧:lst[:] 是做浅拷贝最短的写法。
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)
OUTPUT
[30, 40, 50] [10, 20, 30] [60, 70, 80] [60, 70, 80] [10, 20, 30, 40, 50, 60] [40, 50, 60] [10, 30, 50, 70] [20, 40, 60, 80] [80, 70, 60, 50, 40, 30, 20, 10] [] [60, 70, 80] True False [1, 99, 99, 5] [1, 7, 8, 99, 99, 5] [1, 7, 99, 5]

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-1lst[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]
✂️ Slice Lab — lst[start:stop:step]Slice Lab — lst[start:stop:step]切片实验室 —— lst[start:stop:step]Leave a box empty for its defaultDefault के लिए box ख़ाली छोड़ें留空即使用默认值
lst[::]
Read a slice:Slice पढ़ें:读取切片:
slice assignment:slice assignment:切片赋值: lst[start:stop:step] =
Change a slice:Slice बदलें:修改切片:
🧭
Plain Slice vs Extended Sliceसाधारण Slice बनाम Extended Slice普通切片 vs 扩展切片

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。


SectionSection第 06 节

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() 等内置函数与它们配合使用。

🧰 List Method SimulatorList Method Simulator列表方法模拟器The list keeps its changes — chain as many calls as you likeList अपने बदलाव रखती है — जितने चाहें calls जोड़ें列表会保留修改 —— 可以连续调用任意多次

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)
OUTPUT
['code', 'test', 'deploy', 'review', 'ship'] [1, 2, [3, 4]] [1, 2, 3, 4] [1, 2, 'h', 'i'] ['a', 'b', 'c', 'd'] [1, 3, 2, 1] ValueError: list.remove(x): x not in list 40 10 [20, 30] [1, 1, 2, 3, 4, 5, 6, 9] [9, 6, 5, 4, 3, 2, 1, 1] ['fig', 'kiwi', 'apple', 'strawberry'] None [4, 3, 2, 1] []
⚠️
Mutators Return None — Not the List!Mutators None लौटाते हैं — List नहीं!修改器返回 None —— 不是列表!

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
OUTPUT
3 0 1 ValueError: 'maybe' is not in list Found at 1 5 60 92 398 79.6 3

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)
OUTPUT
[1, 2, 3] [1, 2, 3, 4] [1, 2, 3] [3, 1, 2] list_reverseiterator [2, 1, 3] None

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 前插入 xNone
.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 / sumFunctions: size and totalsFunctions: आकार और जोड़函数:长度与汇总a valueएक मान一个值

SectionSection第 07 节

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 那样给索引号。所以读起来几乎像英语。

🔄 Loop Pattern StepperLoop Pattern Stepper循环模式单步器Edit the lists, then step through the loop line by lineLists बदलें, फिर loop को line-दर-line चलाएँ修改列表,然后逐行单步执行循环
variablesvariables变量
outputoutput输出

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}")
OUTPUT
I love apple I love banana I love cherry 0: apple 1: banana 2: cherry Item #1: apple Item #2: banana Item #3: cherry
❌ C-style (works, but clumsy)C-style (चलता है, पर भद्दा)C 风格(能用,但笨拙)
CodeCode代码
for i in range(len(fruits)):
    print(i, fruits[i])
Needs len() and indexing.len() और indexing चाहिए।需要 len() 和索引。
✅ PythonicPythonicPythonic 写法
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)
OUTPUT
Asha: 92 Ravi: 85 Meena: 78 x 1 y 2 ValueError: zip() argument 2 is longer than argument 1
🤐
zip() Stops Quietlyzip() चुपचाप रुक जाता हैzip() 会悄悄停止

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)
OUTPUT
[1, 4, 9, 16, 25] [1, 4, 9, 16, 25] [4, 16]

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
OUTPUT
First even: 8 8 10 12 99 not found in the list
🚫
Don't Change a List While Looping Over ItLoop करते हुए List न बदलें不要边遍历边修改列表

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)
OUTPUT
[-2, 3, 5] [3, 5]

SectionSection第 08 节

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 Explorer — grid[row][col]Grid Explorer — grid[row][col]网格探索器 —— grid[row][col]Click a cell, change a cell, or loop over the gridCell पर click करें, बदलें, या grid पर loop करें点击单元格、修改单元格,或遍历网格
grid[][]
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)
OUTPUT
1 9 6 [[1, 2, 3], [4, 0, 6], [7, 8, 9]] 3 3 1 2 3 4 0 6 7 8 9 Zero at (1,1) [1, 2, 3, 4, 5] [2, 4, 6, 8, 10] [3, 6, 9, 12, 15] [4, 8, 12, 16, 20] [5, 10, 15, 20, 25]

SectionSection第 09 节

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()
OUTPUT
──────────────────────────────────────────── INVENTORY REPORT ──────────────────────────────────────────── ITEM QTY PRICE $ TOTAL $ apple 12 1.20 14.40 bread 5 3.50 17.50 milk 8 2.80 22.40 eggs 24 4.00 96.00 cheese 3 5.50 16.50 ──────────────────────────────────────────── Grand total: $166.80 Items in stock: 5 Cheapest item: apple ($1.20) Priciest item: cheese ($5.50) Total units: 52 Items under $3: ['apple', 'milk'] First item: apple Last item: cheese Top 3: ['apple', 'bread', 'milk'] Reversed: ['cheese', 'eggs', 'milk', 'bread', 'apple'] Updated (sorted): ['almonds', 'apple', 'bread', 'cheese', 'milk', 'yogurt'] chocolate is out of stock
🐞
A Real Bug This Program Avoidsएक असली Bug जिससे यह Program बचता है本程序避开的一个真实 bug

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”的列表要在修改列表之前构建。(以后你会学到字典,它能把每个名字和价格放在一起。)


SectionSection第 10 节

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

🐍 Python Lists — 8 RulesPython Lists — 8 नियमPython 列表 —— 8 条法则
1
A list stores references, not values. Each slot points to an object somewhere else. That is why one list can mix types, and why aliasing surprises happen.
List references रखती है, मान नहीं। हर slot कहीं और रखे object की ओर इशारा करता है। इसीलिए एक list में types मिल सकते हैं, और aliasing की हैरानियाँ होती हैं।
列表保存的是引用,不是值。每个槽位都指向别处的某个对象。这就是一个列表能混合类型、也会出现别名意外的原因。
2
b = a is NOT a copy. Both names point at the same list. Use a.copy(), a[:] or list(a) for a new list — and copy.deepcopy(a) when it holds other lists.
b = a copy नहीं है। दोनों नाम एक ही list की ओर हैं। नई list के लिए a.copy(), a[:] या list(a) लगाएँ — और जब उसमें दूसरी lists हों तो copy.deepcopy(a)।
b = a 不是复制。两个名字指向同一个列表。要新列表,用 a.copy()、a[:] 或 list(a) —— 列表里还有列表时用 copy.deepcopy(a)。
3
Mutators return None. Never write nums = nums.sort(). Call nums.sort() alone, or use sorted(nums).
Mutators None लौटाते हैं। nums = nums.sort() कभी न लिखें। सिर्फ़ nums.sort() call करें, या sorted(nums) लगाएँ।
修改器返回 None。永远不要写 nums = nums.sort()。单独调用 nums.sort(),或使用 sorted(nums)。
4
The slice stop is exclusive, and slices never crash. lst[2:5] gives indexes 2, 3, 4. Out-of-range bounds are clipped — but a plain index out of range is an IndexError.
Slice का stop शामिल नहीं होता, और slices कभी नहीं रुकतीं। lst[2:5] indexes 2, 3, 4 देता है। सीमा से बाहर के अंक काट दिए जाते हैं — पर सीमा से बाहर का साधारण index IndexError है।
切片的 stop 不包含在内,且切片永不报错。lst[2:5] 给出索引 2、3、4。越界的边界会被截断 —— 但普通索引越界会引发 IndexError。
5
Prefer enumerate() and zip() over range(len(lst)). They are clearer and harder to get wrong. Remember that zip() stops at the shortest list.
range(len(lst)) की जगह enumerate() और zip() चुनें। ये ज़्यादा साफ़ हैं और इनमें ग़लती कम होती है। याद रखें कि zip() सबसे छोटी list पर रुकता है।
优先用 enumerate() 和 zip(),而不是 range(len(lst))。它们更清晰、更不容易出错。记住 zip() 在最短的列表处停止。
6
Never remove items from a list while looping over it. Items get skipped. Build a new list with a comprehension, or loop over lst[:].
Loop करते हुए list से items कभी न हटाएँ। Items छूट जाते हैं। Comprehension से नई list बनाएँ, या lst[:] पर loop करें।
绝不在遍历列表时删除其中的项。会有项被跳过。用推导式构建新列表,或遍历 lst[:]。
7
Build 2-D lists with a comprehension. [[0] * 3] * 3 repeats one row object; [[0] * 3 for _ in range(3)] makes three.
2-D lists comprehension से बनाएँ। [[0] * 3] * 3 एक ही row object दोहराता है; [[0] * 3 for _ in range(3)] तीन बनाता है।
用推导式构建二维列表。[[0] * 3] * 3 重复的是同一个行对象;[[0] * 3 for _ in range(3)] 才会创建三个。
8
Pick the right tool. append() for one item, extend() for many. pop() when you need the removed value, remove() or del when you do not. in to check, index() only when you need the position.
सही औज़ार चुनें। एक item के लिए append(), कई के लिए extend()। हटाया मान चाहिए तो pop(), नहीं चाहिए तो remove() या del। जाँचने के लिए in, जगह चाहिए तभी index()।
选对工具。添加一项用 append(),添加多项用 extend()。需要被删除的值用 pop(),不需要就用 remove() 或 del。检查是否存在用 in,需要位置时才用 index()。
LIVELIVE互动Quick Checkछोटी जाँच小测验

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

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

关于列表的六道题。选择答案查看解释。

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

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 是共享对象,而不是复制。

🐍 Try Python Yourself

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