Imagine storing the marks of 40 students in 40 separate variables β m1, m2, m3 β¦ m40! π΅ Finding the highest mark would need 40 comparisons written by hand. There has to be a better way β and there is: the list! π A list stores MANY values under ONE name, and Python gives you powerful tools to add, remove, search and sort them. This chapter explains how a list differs from a string, how to access, slice and change list elements, what append(), extend(), insert(), pop(), remove() and sort() do, and how to write programs that find the maximum or the mean, or search for an element.
Focus especially on list mutability and aliasing, append() vs extend(), pop() vs remove() vs del, sort() vs sorted(), and the programs (max/min/mean, linear search, frequency count) β revise these carefully.
10.1 π Introduction
A list is an ordered, mutable collection of values enclosed in square brackets [ ] and separated by commas. The values are called elements or items, and they can be of different data types.
marks = [85, 92, 78, 64, 90] # list of integers
fruits = ["apple", "mango", "banana"] # list of strings
mixed = [101, "Riya", 91.5, True] # different types together
empty = [] # an empty list
nested = [1, 2, [3, 4], 5] # a list inside a list
Ordered
Elements keep the order in which they were added; each has an index
IndexedMutable
Elements can be changed, added or removed after the list is created
ChangeableHeterogeneous
One list can hold values of different data types
int with str with floatDuplicates Allowed
The same value can appear more than once
[5 5 5] is validCreating a list from other sequences using the list() function:
print(list("HELLO")) # ['H', 'E', 'L', 'L', 'O']
print(list(range(1, 6))) # [1, 2, 3, 4, 5]
print(list()) # []
Taking a list as input from the user:
# Method 1: using eval() β the user types the list itself, e.g. [10, 20, 30]
L = eval(input("Enter a list: "))
# Method 2: build it element by element
n = int(input("How many elements? "))
L = []
for i in range(n):
L.append(int(input("Enter element: ")))
print(L)
Analogy: A list is like a train π. Each coach (element) has a fixed number (index), coaches can carry different things (passengers, goods), and at the station you can add, remove or replace coaches β the train is still the same train!
10.2 π’ Accessing List Elements β Indexing
Lists use two-way indexing, exactly like strings:
L = [ 10, 20, 30, 40, 50 ]
Forward: 0 1 2 3 4
Backward: -5 -4 -3 -2 -1
L = [10, 20, 30, 40, 50]
print(L[0], L[3], L[-1], L[-2]) # 10 40 50 40
print(len(L)) # 5
# print(L[5]) # β IndexError: list index out of range
10.2.1 Lists are Mutable π
Unlike strings, you can change a list element in place:
L = [10, 20, 30, 40, 50]
L[1] = 200
L[-1] = 500
print(L) # [10, 200, 30, 40, 500]
Strings vs Lists β The Critical Comparison:
| Feature | String | List |
|---|---|---|
| Brackets | Quotes ' ' / " " |
Square brackets [ ] |
| Elements | Only characters | Values of ANY type |
| Mutable? | β No β s[0] = 'X' is a TypeError |
β
Yes β L[0] = 99 works |
| Indexing / slicing | β Same rules | β Same rules |
| Example | "PYTHON" |
[1, "two", 3.0] |
"Why is a list called mutable while a string is called immutable?" β 2-mark question!
Answer: The elements of a list can be changed in place (e.g., L[0] = 5) without creating a new list, so a list is mutable. The characters of a string cannot be changed in place β any change creates a new string β so a string is immutable.
10.3 β List Operations
10.3.1 Concatenation + and Replication * π
A = [1, 2, 3]
B = [4, 5]
print(A + B) # [1, 2, 3, 4, 5] (joins two lists into a NEW list)
print(B * 3) # [4, 5, 4, 5, 4, 5] (repeats the list)
print([0] * 5) # [0, 0, 0, 0, 0] (handy to create a list of zeros)
With +, both operands must be lists. [1, 2] + 3 gives TypeError: can only concatenate list (not "int") to list. Write [1, 2] + [3] instead.
10.3.2 Membership in and not in π
colours = ["red", "green", "blue"]
print("green" in colours) # True
print("Green" in colours) # False (case-sensitive)
print("pink" not in colours) # True
10.3.3 Comparison ==, <, > βοΈ
Lists are compared element by element from the left, until a difference is found.
print([1, 2, 3] == [1, 2, 3]) # True
print([1, 2, 5] > [1, 2, 3]) # True (5 > 3 at index 2)
print([1, 2] < [1, 2, 0]) # True (a shorter prefix is smaller)
print([3] > [1, 9, 9]) # True (3 > 1 at index 0 decides it)
10.3.4 Slicing βοΈ
List slicing works exactly like string slicing: L[start : stop : step] β start included, stop excluded.
L = [ 11, 22, 33, 44, 55, 66, 77 ]
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
| Slice | Result | Explanation |
|---|---|---|
L[1:4] |
[22, 33, 44] |
indices 1, 2, 3 |
L[:3] |
[11, 22, 33] |
first 3 elements |
L[4:] |
[55, 66, 77] |
from index 4 to the end |
L[-3:] |
[55, 66, 77] |
last 3 elements |
L[::2] |
[11, 33, 55, 77] |
every 2nd element |
L[::-1] |
[77, 66, 55, 44, 33, 22, 11] |
reversed copy |
L[5:1:-2] |
[66, 44] |
indices 5, 3 |
Changing a part of a list using slices β only lists allow this, because they are mutable:
L = [1, 2, 3, 4, 5]
L[1:3] = [20, 30, 35] # replace indices 1β2 with THREE values
print(L) # [1, 20, 30, 35, 4, 5]
L[0:2] = [] # replace with nothing β deletes them
print(L) # [30, 35, 4, 5]
A slice always creates a new list. So M = L[:] gives an independent copy of L β changing M will not affect L. (Remember this for the next section!)
10.4 πΆ Traversing a List
Method 1 β Directly over the elements:
marks = [85, 92, 78]
for m in marks:
print(m, end=" ")
# Output: 85 92 78
Method 2 β Using indices (needed when you want to CHANGE elements):
marks = [85, 92, 78]
for i in range(len(marks)):
marks[i] = marks[i] + 5 # add 5 grace marks
print(marks) # [90, 97, 83]
for m in marks: m = m + 5 does NOT change the list! m is just a temporary copy of each value. To change the elements, loop over the indices and assign to marks[i].
10.5 π Aliasing and Copying a List
When you assign one list to another variable with =, Python does NOT make a copy β both names point to the SAME list in memory. This is called aliasing.
A = [1, 2, 3]
B = A # B is an ALIAS of A β same list!
B[0] = 100
print(A) # [100, 2, 3] β A also changed!
print(A is B) # True
graph LR
A["A"]
B["B"]
C["C"]
L1["π [100, 2, 3]\n(one list in memory)"]
L2["π [1, 2, 3]\n(a separate copy)"]
A --> L1
B --> L1
C --> L2
style L1 fill:#F44336,color:#fff
style L2 fill:#4CAF50,color:#fff
To get an independent copy, use any of these:
A = [1, 2, 3]
C = A.copy() # method 1
D = list(A) # method 2
E = A[:] # method 3 (full slice)
C[0] = 100
print(A) # [1, 2, 3] β A is safe
print(C) # [100, 2, 3]
Analogy: Aliasing is like two people sharing one Google Doc π β when one edits it, the other sees the change. Copying is like downloading your own copy β your edits don't affect anyone else!
Watch for aliasing in output questions. If you see B = A followed by a change to B, remember that A changes too. If you see B = A[:] or B = A.copy() or B = list(A), then A stays unchanged.
10.6 π§° List Functions and Methods
10.6.1 Built-in Functions π’
| Function | Description | Example (L = [4, 9, 1, 7]) |
Result |
|---|---|---|---|
len(L) |
Number of elements | len(L) |
4 |
max(L) |
Largest element | max(L) |
9 |
min(L) |
Smallest element | min(L) |
1 |
sum(L) |
Sum of all elements (numbers only) | sum(L) |
21 |
sorted(L) |
Returns a NEW sorted list; L is unchanged |
sorted(L) |
[1, 4, 7, 9] |
list(seq) |
Converts a sequence into a list | list("abc") |
['a', 'b', 'c'] |
names = ["Riya", "Aman", "Zoya"]
print(max(names)) # Zoya (strings compared alphabetically)
print(min(names)) # Aman
# sum(names) # β TypeError β can't add strings with sum()
10.6.2 Adding Elements: append(), extend(), insert() β
| Method | Description | Example (L = [1, 2, 3]) |
L becomes |
|---|---|---|---|
L.append(x) |
Adds ONE element x at the end |
L.append(4) |
[1, 2, 3, 4] |
L.extend(seq) |
Adds EACH element of a sequence at the end | L.extend([4, 5]) |
[1, 2, 3, 4, 5] |
L.insert(i, x) |
Inserts x at index i; the rest shift right |
L.insert(1, 10) |
[1, 10, 2, 3] |
A = [1, 2, 3]
A.append([4, 5]) # adds the whole list as ONE element
print(A) # [1, 2, 3, [4, 5]]
print(len(A)) # 4
B = [1, 2, 3]
B.extend([4, 5]) # adds 4 and 5 separately
print(B) # [1, 2, 3, 4, 5]
print(len(B)) # 5
append() vs extend() β The Critical Comparison:
| Feature | append() |
extend() |
|---|---|---|
| Argument | Any single value | A sequence (list, tuple, stringβ¦) |
| What is added | The argument as ONE element | Each element of the sequence |
| Length increases by | Always 1 | Number of items in the sequence |
L.append("hi") vs L.extend("hi") |
adds 'hi' |
adds 'h' and 'i' |
"Differentiate between append() and extend()." β 2-mark question.
Answer: append() adds its argument as a single element at the end of the list (length increases by 1). extend() adds each element of the given sequence at the end of the list. Example: for L = [1, 2], L.append([3, 4]) gives [1, 2, [3, 4]], while L.extend([3, 4]) gives [1, 2, 3, 4].
List methods like append(), sort() and reverse() change the list in place and return None. So L = L.append(5) makes L equal to None! Just write L.append(5).
10.6.3 Removing Elements: pop(), remove(), clear(), del β
| Way | Description | Example (L = [10, 20, 30, 20]) |
Result |
|---|---|---|---|
L.pop() |
Removes and returns the last element | x = L.pop() |
x = 20, L = [10, 20, 30] |
L.pop(i) |
Removes and returns the element at index i |
x = L.pop(0) |
x = 10, L = [20, 30, 20] |
L.remove(x) |
Removes the first occurrence of the value x |
L.remove(20) |
L = [10, 30, 20] |
L.clear() |
Removes all elements | L.clear() |
L = [] |
del L[i] |
Deletes the element at index i |
del L[1] |
L = [10, 30, 20] |
del L[i:j] |
Deletes a slice | del L[1:3] |
L = [10, 20] |
del L |
Deletes the whole list variable | del L |
L no longer exists |
L = [5, 8, 3]
# L.remove(9) # β ValueError: list.remove(x): x not in list
# L.pop(7) # β IndexError: pop index out of range
pop() vs remove() vs del:
pop()
Removes by INDEX (default: last) and RETURNS the removed value
IndexError if bad indexremove()
Removes by VALUE (first occurrence only); returns None
ValueError if not founddel
A statement (not a method); deletes by index or slice or the whole list
Returns nothing"Differentiate between pop() and remove()." β 2-mark question!
Answer: pop() removes an element by its index (the last element if no index is given) and returns it. remove() removes the first occurrence of the given value and returns nothing (None).
10.6.4 Searching and Counting: index(), count() π
| Method | Description | Example (L = [3, 7, 3, 9, 3]) |
Result |
|---|---|---|---|
L.index(x) |
Index of the first occurrence of x; ValueError if absent |
L.index(9) |
3 |
L.count(x) |
Number of times x occurs |
L.count(3) |
3 |
find() method! π§ find() belongs to strings only. For lists, use index() β and check with in first if you are not sure the value exists: if x in L: print(L.index(x)).
10.6.5 Ordering: sort(), reverse() and sorted() π
| Way | Description | Example (L = [4, 1, 3]) |
Result |
|---|---|---|---|
L.sort() |
Sorts L in place in ascending order |
L.sort() |
L = [1, 3, 4] |
L.sort(reverse=True) |
Sorts L in place in descending order |
L.sort(reverse=True) |
L = [4, 3, 1] |
L.reverse() |
Reverses the order of L in place (no sorting!) |
L.reverse() |
L = [3, 1, 4] |
sorted(L) |
Returns a NEW sorted list; L unchanged |
M = sorted(L) |
M = [1, 3, 4] |
L = [40, 10, 30, 20]
M = sorted(L)
print(L) # [40, 10, 30, 20] β unchanged
print(M) # [10, 20, 30, 40]
L.sort()
print(L) # [10, 20, 30, 40] β changed in place
words = ["banana", "Apple", "cherry"]
words.sort()
print(words) # ['Apple', 'banana', 'cherry'] ('A' = 65 comes before 'b' = 98)
sort() vs sorted() β The Critical Comparison:
| Feature | L.sort() |
sorted(L) |
|---|---|---|
| Type | List method | Built-in function |
| Original list | Changed (sorted in place) | Not changed |
| Returns | None |
A new sorted list |
| Works on | Lists only | Any sequence (list, tuple, stringβ¦) |
"Differentiate between sort() and sorted()." β 2-mark question!
Answer: sort() is a list method that sorts the list in place and returns None. sorted() is a built-in function that returns a new sorted list, leaving the original sequence unchanged.
reverse() does NOT sort in descending order! It only flips the current order. For descending order, use L.sort(reverse=True).
10.7 πͺ Nested Lists
A nested list is a list that contains other lists as its elements. It is useful for storing table-like (2-D) data, such as a matrix or rows of student records.
M = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(M[1]) # [4, 5, 6] β the row at index 1
print(M[1][2]) # 6 β row 1, column 2
print(len(M)) # 3 β number of rows
col 0 col 1 col 2
row 0 [ 1 , 2 , 3 ]
row 1 [ 4 , 5 , 6 ] M[1][2] β 6
row 2 [ 7 , 8 , 9 ]
# Print the matrix row by row using nested loops
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in M:
for value in row:
print(value, end=" ")
print()
1 2 3
4 5 6
7 8 9
10.8 π» Important List Programs
Code Example: max_min_mean.py
# Find the maximum, minimum and mean of numbers in a list (without built-ins)
L = [45, 12, 78, 34, 89, 23]
largest = smallest = L[0]
total = 0
for x in L:
if x > largest:
largest = x
if x < smallest:
smallest = x
total += x
mean = total / len(L)
print("Maximum:", largest)
print("Minimum:", smallest)
print("Mean:", round(mean, 2))
Maximum: 89
Minimum: 12
Mean: 46.83
Code Example: linear_search.py
# Linear search: check each element one by one
L = [34, 7, 23, 32, 5, 62]
key = int(input("Enter the element to search: "))
for i in range(len(L)):
if L[i] == key:
print(key, "found at index", i)
break
else:
print(key, "not found in the list")
# Input 32 β 32 found at index 3
# Input 50 β 50 not found in the list
It compares the key with every element from the start until a match is found. In the worst case (element at the end, or not present) it checks all n elements. It works on unsorted lists too.
Code Example: frequency.py
# Count the frequency of each element in a list
L = [2, 5, 2, 8, 5, 2, 9]
checked = []
for x in L:
if x not in checked:
print(x, "occurs", L.count(x), "time(s)")
checked.append(x)
2 occurs 3 time(s)
5 occurs 2 time(s)
8 occurs 1 time(s)
9 occurs 1 time(s)
Code Example: even_odd_split.py
# Separate even and odd numbers into two lists
L = [11, 24, 35, 46, 57, 68]
even, odd = [], []
for x in L:
if x % 2 == 0:
even.append(x)
else:
odd.append(x)
print("Even:", even) # Even: [24, 46, 68]
print("Odd:", odd) # Odd: [11, 35, 57]
Code Example: remove_duplicates.py
# Create a new list without duplicate values (order kept)
L = [3, 1, 3, 2, 1, 4]
unique = []
for x in L:
if x not in unique:
unique.append(x)
print(unique) # [3, 1, 2, 4]
Code Example: swap_halves.py
# Swap the first half of a list with the second half
L = [1, 2, 3, 4, 5, 6]
mid = len(L) // 2
L = L[mid:] + L[:mid]
print(L) # [4, 5, 6, 1, 2, 3]
"Write a program to find the maximum/minimum/mean", "Write a program for linear search", and "Count the frequency of elements" are the suggested practical programs in the CBSE syllabus β expect at least one as a 3-mark question. Practise writing them WITHOUT using max(), min() and sum() too.
β οΈ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
β B = A creates a copy |
It creates an alias | β
Use A.copy(), list(A) or A[:] for a real copy |
β L = L.append(5) |
append() returns None | β
Just write L.append(5) |
β append() and extend() are the same |
append adds one element; extend adds each item | β
[1].append([2, 3]) β [1, [2, 3]]; extend β [1, 2, 3] |
β remove() takes an index |
remove() takes a VALUE | β
Use pop(i) or del L[i] to remove by index |
β reverse() sorts in descending order |
It only flips the order | β
Use L.sort(reverse=True) |
β sorted(L) changes L |
It returns a new list | β
Use L.sort() to sort in place |
β L.find(x) |
Lists have no find() | β
Use L.index(x) |
β for x in L: x = x * 2 doubles the list |
x is a temporary variable | β
Use for i in range(len(L)): L[i] = L[i] * 2 |
β [1, 2] + 3 |
Can't add a list and an int | β
[1, 2] + [3] |
π Quick Revision
List Basics:
- Ordered, mutable collection in
[ ]; elements can be of any type - Indices: 0 to n β 1 and β1 to βn; slicing
L[start:stop:step]makes a new list - Create with
[ ],list(), oreval(input())
Operators: + (join) Β· * (repeat) Β· in / not in Β· ==, <, > (element by element)
Methods at a Glance:
| Category | Methods |
|---|---|
| Add | append(x), extend(seq), insert(i, x) |
| Remove | pop([i]), remove(x), clear(), del statement |
| Search / count | index(x), count(x) |
| Order | sort(), sort(reverse=True), reverse() |
| Copy | copy() |
| Functions | len(), max(), min(), sum(), sorted(), list() |
Remember:
appendβ 1 element Β·extendβ each elementpopβ by index, returns value Β·removeβ by value, returns Nonesort()β in place, returns None Β·sorted()β new listB = Aβ alias (same list) Β·B = A[:]β copy- Nested list:
M[row][col]
π― Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) What is the output of print([1, 2] * 2)?
β [1, 2, 1, 2]
b) What does L.pop() do when no index is given?
β It removes and returns the last element of the list
c) If L = [5, 3, 5, 1], what is L.index(5)?
β 0 (the first occurrence)
d) Which method adds an element at a specific position?
β insert()
e) What will len([1, [2, 3], 4]) return?
β 3
Q2: Output Based [2 marks]
Q: Write the output of the following code:
L = [10, 20, 30]
L.append([40, 50])
print(L, len(L))
L.extend([60, 70])
print(L[-3:])
Answer:
[10, 20, 30, [40, 50]] 4
[[40, 50], 60, 70]
Q3: Output Based [2 marks]
Q: Write the output of the following code:
A = [1, 2, 3, 4]
B = A
C = A[:]
B[0] = 100
C[1] = 200
print(A)
print(B)
print(C)
Answer:
[100, 2, 3, 4]
[100, 2, 3, 4]
[1, 200, 3, 4]
(B is an alias of A, so changing B changes A. C is a separate copy.)
Q4: Output Based [3 marks]
Q: Write the output of the following code:
L = [3, 8, 1, 6, 8, 2]
L.remove(8)
x = L.pop(1)
L.insert(2, x * 2)
print(L)
L.sort(reverse=True)
print(L, L.count(8))
del L[1:3]
print(L)
Answer:
[3, 6, 2, 8, 2]
[8, 6, 3, 2, 2] 1
[8, 2, 2]
Q5: Program [3 marks]
Q: Write a program to input a list of numbers and swap elements at even positions with the elements at the next odd positions (e.g., [1, 2, 3, 4, 5, 6] becomes [2, 1, 4, 3, 6, 5]).
L = eval(input("Enter a list: "))
for i in range(0, len(L) - 1, 2):
L[i], L[i + 1] = L[i + 1], L[i]
print(L)
# Input [1, 2, 3, 4, 5, 6] β [2, 1, 4, 3, 6, 5]
βοΈ Practice Problems
-
Differentiate between a list and a string (any three points).
-
If
L = [15, 25, 35, 45, 55, 65], write the output of: (a)L[2:5](b)L[-4:-1](c)L[::-2](d)L[10:] -
Write the output of:
L = [1, 2, 3]; L.insert(10, 4); L.insert(-1, 5); print(L)and explain the result. -
Write a program to input a list of numbers and print the second largest number without using
sort(). -
Write a program to input a list and shift all its elements one position to the left (the first element moves to the end).
-
Write a program to find the sum of all the elements of a 3 Γ 3 nested list (matrix) and print the sum of each row.
-
Write a program to input a list of names and print only the names that start with a vowel.
-
Explain with an example the difference between
del L[2],L.pop(2)andL.remove(2). -
Write a program that uses linear search to count how many times a given number occurs in a list and prints all the positions where it occurs.
-
Write a program to input a list of integers and create a new list containing the squares of only the positive numbers.