Neural Sync Active
Week 6: Lists & Slicing
Registry Synced
Week 6: Lists & Slicing
4360 words
22 min read
2026-09-12
Reading compass
Now · TL;DR
Programming in Python — Week 6: Lists & Slicing
The official IITM syllabus lists Week 6: Basic Collections in Python.
This week changes the scale of your programs. Instead of keeping one value in one variable, Python can keep many related values inside one collection.
TL;DR
Before collections:
pythona = 10 b = 20 c = 30
With a collection:
pythonvalues = [10, 20, 30]
Now we can:
- store many values together
- access individual elements
- iterate through them
- modify them
- search them
- count them
- slice subsequences
- build new collections
- combine collections with loops and conditions
The central model is:
The most important Python collection for this week is the list.
1. Why collections?
Suppose we have marks of five students.
Without a collection:
pythonm1 = 67 m2 = 81 m3 = 45 m4 = 90 m5 = 73
This becomes inconvenient if there are:
students.
With a list:
pythonmarks = [67, 81, 45, 90, 73]
Now the data has one name:
pythonmarks
and can be processed systematically.
2. List
A Python list is an ordered collection of elements.
Example:
pythonnumbers = [10, 20, 30, 40]
The order matters.
Conceptually:
textindex: 0 1 2 3 value: 10 20 30 40
3. Zero-based indexing
Python lists use zero-based indexing.
For:
pythonnumbers = [10, 20, 30, 40]
we have:
pythonnumbers[0] # 10 numbers[1] # 20 numbers[2] # 30 numbers[3] # 40
So the first element is at index:
not 1.
4. Last valid positive index
For a list of length:
valid non-negative indices are:
So:
5. len()
Python:
pythonlen(values)
returns the number of elements.
Example:
pythonvalues = [5, 8, 2, 9] print(len(values))
Output:
text4
6. Accessing elements
pythonx = [4, 7, 9] print(x[0]) print(x[2])
Output:
text4 9
7. Index vs value
For:
pythonx = [4, 7, 9]
in:
pythonx[1]
1 is the index.7 is the value stored at that index.Do not confuse:
textposition/index
with:
textelement/value
8. Index error
For:
pythonx = [4, 7, 9]
valid positive indices are:
text0, 1, 2
So:
pythonx[3]
is out of bounds and raises an error.
9. Negative indexing
Python also supports negative indices.
For:
pythonx = [10, 20, 30, 40]
pythonx[-1] # 40 x[-2] # 30 x[-3] # 20
So:
10. Positive and negative index map
For:
pythonx = [10, 20, 30, 40]
textvalue: 10 20 30 40 positive: 0 1 2 3 negative: -4 -3 -2 -1
11. Lists are mutable
A Python list can be changed after creation.
Example:
pythonx = [10, 20, 30] x[1] = 99 print(x)
Output:
text[10, 99, 30]
This property is called mutability.
12. Mutation
Mutation means changing an existing object.
pythonx[1] = 99
changes the list itself.
It does not merely calculate a new temporary value.
13. Different element types
Python lists can contain values of different types:
pythonx = [10, "hello", True, 3.5]
However, many numerical algorithms naturally use collections of similar values.
14. Empty list
pythonx = []
represents a list containing zero elements.
Its length:
pythonlen(x)
is:
15. Creating a list
Literal syntax:
pythonnumbers = [1, 2, 3]
Strings:
pythonnames = ["A", "B", "C"]
Booleans:
pythonflags = [True, False, True]
16. Iterating over list values
Instead of:
pythonfor i in range(len(values)): print(values[i])
Python lets us directly iterate over values:
pythonfor x in values: print(x)
This is often cleaner when index itself is unnecessary.
17. Example
pythonvalues = [5, 8, 3] for x in values: print(x)
Output:
text5 8 3
Loop variable
x receives each element in order.18. Value iteration vs index iteration
Value iteration
pythonfor x in values: print(x)
Use when you only need elements.
Index iteration
pythonfor i in range(len(values)): print(i, values[i])
Use when you need positions as well.
19. Sum a list manually
pythonvalues = [3, 8, 2, 7] total = 0 for x in values: total += x print(total)
Result:
20. Built-in sum()
Python also provides:
pythonsum(values)
Example:
pythonvalues = [3, 8, 2, 7] print(sum(values))
Output:
text20
Understanding the manual accumulator remains important for algorithmic reasoning.
21. Average
pythonvalues = [10, 20, 30, 40] average = sum(values) / len(values) print(average)
Result:
This assumes the list is non-empty.
22. Empty-list danger
For:
pythonvalues = []
this is invalid:
pythonsum(values) / len(values)
because:
Always consider the zero-element case.
23. Minimum and maximum
Python provides:
pythonmin(values) max(values)
Example:
pythonvalues = [4, 9, 2, 7] print(min(values)) print(max(values))
Output:
text2 9
24. Manual maximum
pythonmaximum = values[0] for x in values: if x > maximum: maximum = x
This assumes:
pythonvalues
is non-empty.
The algorithm is the same running-maximum pattern from earlier weeks.
25. Membership with in
Python:
pythonx in values
returns a Boolean.
Example:
pythonvalues = [5, 8, 2] print(8 in values) print(10 in values)
Output:
textTrue False
26. not in
pythonx not in values
is true if the element does not occur.
Example:
pythonif 10 not in values: print("Missing")
27. Linear search intuition
Membership can be understood as checking elements one by one until:
- a match is found
- or the collection ends
Conceptually:
pythonfound = False for x in values: if x == target: found = True break
28. Count matches manually
pythoncount = 0 for x in values: if x == target: count += 1
This computes how many times
target occurs.29. Built-in .count()
Lists also provide:
pythonvalues.count(target)
Example:
pythonvalues = [2, 5, 2, 2, 8] print(values.count(2))
Output:
text3
30. .index()
pythonvalues.index(x)
returns the index of the first occurrence.
Example:
pythonvalues = [5, 8, 3, 8] print(values.index(8))
Output:
text1
It finds the first 8.
31. .index() when value is absent
If an element does not exist:
pythonvalues.index(100)
raises an error.
A safe pattern:
pythonif 100 in values: print(values.index(100))
32. append()
To add one element at the end:
pythonvalues.append(x)
Example:
pythonvalues = [1, 2] values.append(3) print(values)
Output:
text[1, 2, 3]
33. Repeated list construction
pythonvalues = [] for i in range(5): values.append(i * i) print(values)
Output:
text[0, 1, 4, 9, 16]
This pattern constructs a collection incrementally.
34. Filter into a new list
pythonnumbers = [3, 8, 5, 10, 2] evens = [] for x in numbers: if x % 2 == 0: evens.append(x) print(evens)
Output:
text[8, 10, 2]
35. Transformation into a new list
pythonnumbers = [1, 2, 3, 4] squares = [] for x in numbers: squares.append(x ** 2)
Result:
text[1, 4, 9, 16]
This is a map-like transformation:
36. Filter vs transform
Filter
Keep only some values:
pythonif condition: result.append(x)
Transform
Create a changed value for every input:
pythonresult.append(f(x))
These are fundamental collection-processing patterns.
37. insert()
pythonvalues.insert(index, value)
inserts an element at a chosen position.
Example:
pythonvalues = [10, 30] values.insert(1, 20) print(values)
Output:
text[10, 20, 30]
Existing elements shift right.
38. remove()
pythonvalues.remove(x)
removes the first matching value.
Example:
pythonvalues = [2, 5, 2, 9] values.remove(2) print(values)
Result:
text[5, 2, 9]
Only the first
2 is removed.39. pop()
pythonvalues.pop()
removes and returns the last element.
Example:
pythonvalues = [10, 20, 30] x = values.pop()
Now:
textx = 30 values = [10, 20]
40. pop(index)
pythonvalues.pop(1)
removes the element at index 1.
Example:
pythonvalues = [10, 20, 30] x = values.pop(1)
Then:
textx = 20 values = [10, 30]
41. del
Python also allows:
pythondel values[i]
Example:
pythonvalues = [10, 20, 30] del values[1]
Result:
text[10, 30]
42. Remove by value vs position
By value
pythonvalues.remove(20)
By index
pythonvalues.pop(1)
or:
pythondel values[1]
Do not confuse these operations.
43. Concatenation
Lists can be combined:
pythona = [1, 2] b = [3, 4] c = a + b
Result:
text[1, 2, 3, 4]
44. Repetition
python[0] * 5
produces:
text[0, 0, 0, 0, 0]
Useful for initializing fixed-size simple lists.
45. Slicing
A slice extracts a portion of a sequence.
pythonvalues[start:stop]
Like
range, the stop index is excluded.Example:
pythonvalues = [10, 20, 30, 40, 50] print(values[1:4])
Output:
text[20, 30, 40]
46. Slice endpoint rule
For:
pythonvalues[a:b]
indices included are:
Again:
47. Omitted slice endpoints
pythonvalues[:3]
means from beginning through index 2.
pythonvalues[2:]
means from index 2 through end.
48. Full copy slice
pythonvalues[:]
creates a shallow copy of the list.
This matters because simple assignment behaves differently.
49. Aliasing
Consider:
pythona = [1, 2, 3] b = a
Now
a and b refer to the same list object.If:
pythonb[0] = 99
then:
pythona
also appears as:
text[99, 2, 3]
50. Assignment does not necessarily copy a list
This:
pythonb = a
copies the reference, not the list contents into an independent object.
Conceptually:
texta ─┐ ├──> [1,2,3] b ─┘
51. Shallow copy
A simple independent outer-list copy:
pythonb = a[:]
or:
pythonb = a.copy()
Now changing:
pythonb[0]
does not change:
pythona[0]
for a flat list of immutable elements.
52. Aliasing trace
pythona = [1, 2] b = a b.append(3) print(a)
Output:
text[1, 2, 3]
because both names reference the same mutable object.
53. Copy trace
pythona = [1, 2] b = a.copy() b.append(3) print(a) print(b)
Output:
text[1, 2] [1, 2, 3]
54. Slicing with step
General form:
pythonvalues[start:stop:step]
Example:
pythonvalues = [0, 1, 2, 3, 4, 5] values[0:6:2]
produces:
text[0, 2, 4]
55. Reverse with slicing
pythonvalues[::-1]
returns a reversed copy.
Example:
python[1, 2, 3][::-1]
gives:
text[3, 2, 1]
56. Strings are sequences too
A string is also an ordered sequence.
pythontext = "python"
Indexes:
textp y t h o n 0 1 2 3 4 5
So:
pythontext[0]
returns:
text'p'
57. String slicing
pythontext = "python" print(text[1:4])
Output:
textyth
Same start-inclusive, stop-exclusive principle.
58. Strings are immutable
Unlike lists:
pythontext[0] = "P"
is not allowed.
Strings cannot be modified element-by-element.
Instead create a new string.
This is a key difference:
59. Iterate over characters
pythonfor ch in "python": print(ch)
Output:
textp y t h o n
So loops work over sequences beyond
range().60. Count vowels
pythontext = input() count = 0 for ch in text.lower(): if ch in "aeiou": count += 1 print(count)
This combines:
- strings
- iteration
- membership
- conditionals
- counters
61. String membership
python"a" in "cat"
is:
textTrue
and:
python"z" in "cat"
is:
textFalse
62. String concatenation
pythona = "hello" b = "world" c = a + " " + b
Result:
text"hello world"
63. Building strings iteratively
pythonresult = "" for ch in text: if ch != " ": result += ch
This creates a new string without spaces.
Because strings are immutable, each concatenation conceptually constructs a new string value.
64. Tuple
Python also has tuples.
Example:
pythonpoint = (3, 5)
A tuple is ordered, like a list, but typically immutable.
65. Tuple indexing
pythonpoint = (3, 5) print(point[0]) print(point[1])
Output:
text3 5
66. Tuple immutability
This is not allowed:
pythonpoint[0] = 10
because tuples are immutable.
So:
| Type | Ordered | Mutable |
|---|---|---|
| List | Yes | Yes |
| Tuple | Yes | No |
| String | Yes | No |
67. Tuple packing
pythonpoint = 3, 5
creates a tuple conceptually equivalent to:
pythonpoint = (3, 5)
68. Tuple unpacking
pythonx, y = (3, 5)
gives:
textx = 3 y = 5
This is useful for structured multiple values.
69. Swap revisited
Python:
pythona, b = b, a
uses tuple-like packing/unpacking semantics.
Right side is evaluated first, then values are assigned.
70. Nested collections
Collections can contain other collections.
Example:
pythonmatrix = [ [1, 2], [3, 4] ]
This is a list containing two lists.
71. Matrix access
pythonmatrix[0]
gives:
text[1, 2]
Then:
pythonmatrix[0][1]
gives:
text2
First index chooses row.
Second chooses element inside that row.
72. Nested list traversal
pythonfor row in matrix: for x in row: print(x)
This uses nested loops to traverse a nested collection.
73. Index-based matrix traversal
pythonfor i in range(len(matrix)): for j in range(len(matrix[i])): print(matrix[i][j])
Useful when row/column positions matter.
74. List of strings
pythonnames = ["Asha", "Ravi", "Meera"]
Then:
pythonnames[1]
gives:
text"Ravi"
and:
pythonnames[1][0]
gives:
text"R"
because a string itself is a sequence.
75. List methods mutate the list
Consider:
pythonx = [3, 1, 2] x.sort()
Now:
pythonx
becomes:
text[1, 2, 3]
The original list object was modified.
76. sorted()
Python also provides:
pythonsorted(x)
which returns a new sorted list without necessarily modifying
x.Example:
pythonx = [3, 1, 2] y = sorted(x)
Then:
textx = [3, 1, 2] y = [1, 2, 3]
77. .sort() vs sorted()
.sort()
pythonx.sort()
mutates list
x.sorted()
pythony = sorted(x)
returns a sorted result.
This distinction is a classic exam/debugging issue.
78. Reverse
Mutation:
pythonx.reverse()
changes the list.
Alternative:
pythonx[::-1]
creates a reversed copy.
Again:
79. extend()
pythona.extend(b)
adds all elements of
b to the end of a.Example:
pythona = [1, 2] a.extend([3, 4])
Result:
text[1, 2, 3, 4]
80. append() vs extend()
Starting:
pythona = [1, 2]
Append
pythona.append([3, 4])
gives:
text[1, 2, [3, 4]]
Extend
pythona.extend([3, 4])
gives:
text[1, 2, 3, 4]
Very different results.
81. Nested element created by append
pythona.append([3, 4])
adds one element.
That one element happens to itself be a list.
So length increases by:
not 2.
82. List comprehension — useful Python feature
A concise way to build lists:
pythonsquares = [x ** 2 for x in range(5)]
Result:
text[0, 1, 4, 9, 16]
This is equivalent in spirit to:
pythonsquares = [] for x in range(5): squares.append(x ** 2)
83. Comprehension with filter
pythonevens = [x for x in range(10) if x % 2 == 0]
Result:
text[0, 2, 4, 6, 8]
This combines transformation/collection construction with filtering.
84. Do not let compact syntax hide the algorithm
When tracing:
python[x ** 2 for x in values if x > 0]
mentally expand it:
pythonresult = [] for x in values: if x > 0: result.append(x ** 2)
The expanded algorithm is easier to reason about.
85. Sequence equality
Lists compare element-by-element.
Example:
python[1, 2, 3] == [1, 2, 3]
is:
textTrue
But:
python[1, 2, 3] == [3, 2, 1]
is:
textFalse
because order matters.
86. Membership checks elements, not positions
For:
pythonx = [10, 20, 30]
python20 in x
asks whether value 20 occurs.
It does not ask whether index 20 exists.
Common mistake: first element index is 1
Wrong:
pythonx[1]
if you intend the first element.
Correct:
pythonx[0]
Python indexing begins at zero.
Common mistake: last index equals length
For:
pythonlen(x) == 5
last valid positive index is:
So:
pythonx[len(x)]
is out of bounds.
Correct last element:
pythonx[len(x) - 1]
or:
pythonx[-1]
Common mistake: modifying a string element
Wrong:
pythontext[0] = "A"
Strings are immutable.
Create a new string instead.
Common mistake: assuming assignment copies list
pythonb = a
does not create an independent list copy.
Mutations through one name can appear through the other.
Common mistake:
append returns new listThis pattern is wrong:
pythonx = x.append(5)
append() mutates x; it does not return the new list for assignment in the way beginners often expect.After this,
x can become:pythonNone
because the method's return value is assigned back.
Correct:
pythonx.append(5)
92. Same issue with .sort()
Wrong:
pythonx = x.sort()
Correct:
pythonx.sort()
or:
pythonx = sorted(x)
Know whether an operation mutates or returns a new collection.
Common mistake: remove by index
pythonx.remove(2)
means:
remove the first value equal to 2
not:
remove index 2
Use:
pythonx.pop(2)
or:
pythondel x[2]
for position-based removal.
Common mistake: modifying list while iterating over it
Example:
pythonfor x in values: if x < 0: values.remove(x)
This can behave unexpectedly because list positions shift during traversal.
A safer pattern is often to build a new filtered list:
pythonresult = [] for x in values: if x >= 0: result.append(x)
Common mistake: slice stop assumed inclusive
pythonx[1:4]
contains indices:
not index 4.
Same half-open interval logic as
range().Common mistake: confuse append and concatenate
Starting:
pythonx = [1, 2]
pythonx.append([3, 4])
and:
pythonx = x + [3, 4]
do not produce the same structure.
First:
text[1, 2, [3, 4]]
Second:
text[1, 2, 3, 4]
Common mistake: nested indexing order
For:
pythonmatrix[i][j]
read it as:
- retrieve
matrix[i] - from that inner collection retrieve
[j]
Do not treat it as one magical two-dimensional primitive.
Common mistake: empty collection assumptions
Functions like:
pythonmin([]) max([])
have no meaningful ordinary result and raise errors.
Always check whether an algorithm requires a non-empty collection.
99. Worked trace — mutation
pythonx = [2, 4, 6] x.append(8) x[1] = 10 x.pop() print(x)
Trace:
text[2,4,6] ↓ append 8 [2,4,6,8] ↓ x[1] = 10 [2,10,6,8] ↓ pop() [2,10,6]
Output:
text[2, 10, 6]
100. Worked trace — aliasing
pythona = [1, 2] b = a a.append(3) b[0] = 9 print(a) print(b)
Both names refer to same object.
Final:
text[9, 2, 3] [9, 2, 3]
101. Worked trace — copy
pythona = [1, 2] b = a.copy() a.append(3) b[0] = 9
Final:
texta = [1, 2, 3] b = [9, 2]
Different objects.
102. Worked trace — filtering
pythonx = [5, -2, 7, 0, -1] y = [] for value in x: if value >= 0: y.append(value)
Trace:
- 5 → keep
- -2 → skip
- 7 → keep
- 0 → keep
- -1 → skip
Final:
text[5, 7, 0]
103. Worked trace — transformation
pythonx = [1, 3, 5] y = [] for value in x: y.append(value + 2)
Final:
text[3, 5, 7]
Input collection remains:
text[1, 3, 5]
104. Collection-processing pipeline
A useful mental model:
textcollection ↓ iterate ↓ filter? ↓ transform? ↓ accumulate / append ↓ result
This pattern appears constantly in Python and later data science.
105. Lists connect iteration to data
Before Week 6:
pythonfor i in range(10):
mostly meant:
iterate over generated integers.
Now:
pythonfor student in students:
means:
iterate over actual stored data.
That is a major conceptual transition.
106. Complexity intuition
Accessing:
pythonx[i]
is conceptually direct.
But searching:
pythontarget in x
may need to inspect many elements.
For a list of length n, a linear search may inspect up to:
elements.
This helps explain why data structure choice eventually matters.
107. Collection invariants
Suppose we build:
pythonpositives = []
and append only when:
pythonx > 0
Then after every iteration:
every element currently inpositivesis positive.
That invariant helps reason about correctness.
108. Week 5 → Week 6 transition
Week 5:
textgenerate/control repeated computation
Week 6:
textstore many values + iterate over stored values + modify and transform collections
Conceptually:
textITERATION + COLLECTIONS ↓ DATA PROCESSING
109. Compact list cheat sheet
pythonx = [10, 20, 30] len(x) x[0] x[-1] x[1] = 99 x.append(40) x.insert(1, 15) x.remove(20) x.pop() x.pop(1) 10 in x x.count(10) x.index(10) x[1:3] x[::-1] x.sort() sorted(x) x.copy()
110. Core collection patterns
Traverse values
pythonfor x in values: ...
Traverse indices
pythonfor i in range(len(values)): ...
Filter
pythonresult = [] for x in values: if condition: result.append(x)
Transform
pythonresult = [] for x in values: result.append(f(x))
Reduce / accumulate
pythontotal = 0 for x in values: total += x
Search
pythonfor x in values: if x == target: ... break
111. What you should actually master
By the end of Python Week 6, you should be able to:
- Explain why collections are useful.
- Create Python lists.
- Understand zero-based indexing.
- Use positive and negative indices.
- Use
len(). - Access and modify list elements.
- Understand list mutability.
- Traverse lists directly.
- Traverse lists by index.
- Sum/count/filter/search collection values.
- Use membership with
in. - Use
append,insert,remove,pop, anddel. - Distinguish removal by value from removal by index.
- Concatenate lists.
- Slice lists.
- Understand stop-exclusive slice semantics.
- Understand aliasing.
- Make a simple independent list copy.
- Distinguish
.sort()fromsorted(). - Distinguish
append()fromextend(). - Treat strings as immutable sequences.
- Iterate and slice strings.
- Understand basic tuples and unpacking.
- Work with nested lists.
- Combine collections with loops and conditionals.
- Recognize common mutation-related bugs.
If these are comfortable, Programming in Python Week 6 is under control.
Quick Recall & Flashcards
Test your active recall before proceeding to practice problems. Format:
Question :: Answer.- Week 6 Diagnostic: For list
L = [1, 2, 3, 4, 5], what doesL[1:4]return? :: Answer: A — SlicingL[1:4]includes index 1, 2, 3 (values 2, 3, 4) and excludes index 4. - Week 6 Diagnostic: If
A = [1, 2], andB = A, and thenB.append(3)is run, what is the length ofA? :: Answer: 3 —B = Acreates an alias to the exact same list in memory. ModifyingBmutatesA, solen(A) = 3.
Practice & Self-Check
Attempt these diagnostic questions to verify your operational understanding.
1
Question 1
For list
L = [1, 2, 3, 4, 5], what does L[1:4] return?MCQ
3 Unit Assessment
A. [2, 3, 4]
B. [1, 2, 3]
C. [2, 3, 4, 5]
D. [1, 2, 3, 4]
2
Question 2
If
A = [1, 2], and B = A, and then B.append(3) is run, what is the length of A?NAT
3 Unit Assessment