1.2.21Introduction to Programming (Python)

Lists — creation, indexing, slicing, mutability

2,235 words10 min readdifficulty · medium2 backlinks

WHAT is a list?

WHY does a list exist? Single variables hold one value. The moment you have many related values (scores of 30 students, pixels in a row), you need a container that keeps them in order and lets you grab any one by position. That is exactly a list.


HOW indexing works (and WHY it starts at 0)

 list:     a[0]   a[1]   a[2]   a[3]
 letters: ['p',   'y',   't',   'h']
 forward:   0      1      2      3
 backward: -4     -3     -2     -1

HOW slicing works


HOW mutability works (the part that bites people)


Figure — Lists — creation, indexing, slicing, mutability

Forecast-then-Verify


80/20 — the 20% you use constantly

  • a[i] read/write one box · a[i:j] slice (copy) · a[:] full copy
  • negative indices count from the end · slicing never raises on bad range
  • lists are mutable; = shares, [:]/.copy()/list() copy
  • append mutates & returns None; + makes a new list

Flashcards

What symbol creates a list literal?
Square brackets [] with comma-separated items.
Why does indexing start at 0?
An index is an offset (distance from start); the first item is 0 steps away.
Convert a[-k] to a positive index for length n.
a[n-k] (so a[-1]=a[n-1]).
What does a[start:stop:step] include?
Items from start up to but NOT including stop, stepping by step; returns a NEW list.
Length of slice a[start:stop]?
stop - start (when both in range).
What does a[::-1] do and why?
Reverses the list; step -1 walks from end to start.
Does an out-of-range slice raise an error?
No — slices are clamped to valid range; only single-index access raises IndexError.
What does it mean that lists are mutable?
Their contents can change in place without making a new object (e.g. a[0]=9, a.append()).
After b = a; b[0]=9, what is a[0]?
9b and a are two names for the SAME list.
How do you make an independent copy of list a?
a[:], a.copy(), or list(a) (shallow copy).
What does a.append(x) return?
None (it mutates in place); never write a = a.append(x).
Difference between a.append(x) and a = a + [x]?
append edits the existing list; + builds a brand-new list and rebinds the name.

Recall Feynman: explain to a 12-year-old

A list is a row of numbered lockers in a hallway. The first locker is number 0 (it's "0 steps in"). You can open any locker by its number and put a new thing inside — that's "mutable," the lockers stay but their stuff can change. A slice is like saying "give me lockers 2 up to but not including 5" — you get copies of those things in a little bag. And if you give your friend the map to the same hallway (b = a), when they swap a locker's contents, your lockers change too, because it was the same hallway all along. To get your own private hallway, you photocopy everything with a[:].

Connections

  • Strings — indexing & slicing (same offset/half-open rules, but strings are immutable)
  • Tuples (ordered like lists but immutable)
  • List methods — append, insert, pop, sort
  • Shallow vs Deep copy (a[:] copies the list but not nested lists)
  • for loops (iterating over list items)
  • Mutability & function arguments (passing lists into functions edits the original)

Concept Map

written with

items can be

position matters

editable in place

access by

is an

first box is

from the end

identity

extract range

returns

half-open rule

gives

List: ordered mutable container

Square brackets and commas

Any or mixed types

Ordered

Mutable

Indexing

Offset from start

Index 0

Negative index

a of minus k equals a of n minus k

Slicing start stop step

New list

stop excluded

Length equals stop minus start

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, ek list Python ka sabse kaam aane wala container hai — ise samjho ek line mein lage numbered lockers ki tarah. Har locker mein ek cheez rakh sakte ho, aur har locker ka ek number (index) hota hai. Important baat: counting 0 se start hoti hai, kyun ki index actually "start se kitne kadam" ko batata hai — pehla element 0 kadam dur hai, isliye uska index 0 hai. Negative index end se ginta hai: a[-1] matlab last wala, aur formula simple hai — a[-k] barabar a[n-k].

Slicing ka rule yaad rakho: a[start:stop:step] mein stop include nahi hota. Isliye a[2:5] deta hai indices 2, 3, 4 — length seedhi stop - start = 3. Aur mast baat — slicing kabhi error nahi deta agar range bahar chali jaaye, Python khud clamp kar deta hai. Lekin single index a[100] galat ho to IndexError aata hai. a[::-1] poori list ulti kar deta hai (reverse).

Sabse bada trap hai mutability. List "mutable" hai matlab uske andar ki cheezein badal sakti ho bina nayi list banaye. Jab tum likhte ho b = a, to nayi list nahi banti — b aur a dono ek hi list ko point karte hain. Ab b[0] = 99 karoge to a bhi badal jaayega! Confusion isliye hoti hai kyunki numbers/strings ke saath aisa nahi hota. Agar sach mein alag copy chahiye to a[:], a.copy(), ya list(a) use karo.

Yaad rakho: a.append(x) list ko jagah par badalta hai aur None return karta hai — isliye kabhi a = a.append(x) mat likhna, warna a None ban jaayega. Ye chhoti baatein interviews aur real code dono mein bahut bachati hain.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections