📦 Unit 2 – Strings, Lists, Tuples & Dictionaries · Lesson 22
Nested Lists, Copying & List Programs
Nested lists
A list can contain other lists. Such a nested list is perfect for tables — rows and columns — like marks of many students in many subjects.
| [0] Eng | [1] Maths | [2] CS | |
|---|---|---|---|
| marks[0] | 78 | 85 | 90 |
| marks[1] | 66 | 72 | 81 |
| marks[2] | 90 | 95 | 99 |
Python
marks = [[78, 85, 90], # student 1: Eng, Maths, CS
[66, 72, 81], # student 2
[90, 95, 99]] # student 3
print(marks[1]) # whole row of student 2
print(marks[1][2]) # student 2, CS
print(marks[2][0], len(marks), len(marks[0]))[66, 72, 81]
81
90 3 3
Traversing a nested list
Python
marks = [[78, 85, 90], [66, 72, 81], [90, 95, 99]]
for row in marks:
for m in row:
print(m, end='\t')
print('| total =', sum(row))78 85 90 | total = 253
66 72 81 | total = 219
90 95 99 | total = 284
Copying lists: alias vs copy
Python
a = [1, 2, 3]
alias = a # same list, two names
copy1 = a[:] # slicing makes a copy
copy2 = list(a) # list() makes a copy
copy3 = a.copy() # copy() method
a.append(4)
print('a :', a)
print('alias :', alias)
print('copies:', copy1, copy2, copy3)
print(alias is a, copy1 is a)a : [1, 2, 3, 4]
alias : [1, 2, 3, 4]
copies: [1, 2, 3] [1, 2, 3] [1, 2, 3]
True False
b = a (alias)
- No new list is made
- Both names point to ONE list
- Change through one name is seen by the other
- b is a → True
b = a[:] / list(a) / a.copy()
- A new list is made
- Two separate lists with same values
- Changing one does not affect the other
- b is a → False
📌 Note
These are shallow copies: for nested lists the inner lists are still shared. Use import copy; copy.deepcopy(L) for a completely independent copy.
List as an argument to a function
Python
def increase(prices, percent):
for i in range(len(prices)):
prices[i] = round(prices[i] * (1 + percent / 100), 2)
def new_list(prices):
prices = [0, 0] # re-assigns the LOCAL name only
return prices
p = [100, 250, 80]
increase(p, 10)
print(p)
print(new_list(p), p)[110.0, 275.0, 88.0]
[0, 0] [110.0, 275.0, 88.0]
Linear search
Check items one by one from the start until the key is found.
Python
nums = [34, 7, 89, 21, 56, 7]
key = int(input('Search for: '))
found = False
for i in range(len(nums)):
if nums[i] == key:
print(key, 'found at index', i)
found = True
break
if not found:
print(key, 'not found')Search for: 21
21 found at index 3
Frequency and removing duplicates
Python
data = [4, 2, 4, 9, 2, 4, 7]
seen = []
for x in data:
if x not in seen:
seen.append(x)
print(x, 'occurs', data.count(x), 'time(s)')
print('Without duplicates:', seen)4 occurs 3 time(s)
2 occurs 2 time(s)
9 occurs 1 time(s)
7 occurs 1 time(s)
Without duplicates: [4, 2, 9, 7]
Largest and second largest (without sorting)
Python
nums = [45, 89, 23, 89, 67, 12]
first = second = float('-inf')
for x in nums:
if x > first:
second = first
first = x
elif first > x > second:
second = x
print('Largest:', first, '| Second largest:', second)Largest: 89 | Second largest: 67
float('-inf') is "minus infinity", smaller than every number — a safe starting value.
Swapping and rotating
Python
L = [1, 2, 3, 4, 5, 6]
half = len(L) // 2
print('Swap halves :', L[half:] + L[:half])
print('Rotate left :', L[1:] + L[:1])
print('Rotate right:', L[-1:] + L[:-1])
for i in range(0, len(L) - 1, 2): # swap neighbours
L[i], L[i + 1] = L[i + 1], L[i]
print('Swap pairs :', L)Swap halves : [4, 5, 6, 1, 2, 3]
Rotate left : [2, 3, 4, 5, 6, 1]
Rotate right: [6, 1, 2, 3, 4, 5]
Swap pairs : [2, 1, 4, 3, 6, 5]
Matrix addition and transpose
Python
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
S = [[A[i][j] + B[i][j] for j in range(2)] for i in range(2)]
T = [[A[j][i] for j in range(2)] for i in range(2)] # transpose
print('A + B =', S)
print('Transpose of A =', T)A + B = [[6, 8], [10, 12]]
Transpose of A = [[1, 3], [2, 4]]
Menu-driven list program
Python
items = []
while True:
print('1-Add 2-Delete 3-Show 4-Exit')
ch = input('Choice: ')
if ch == '1':
items.append(input('Item: '))
elif ch == '2':
it = input('Item to delete: ')
if it in items:
items.remove(it)
else:
print('Not in list')
elif ch == '3':
print('List:', items)
elif ch == '4':
break1-Add 2-Delete 3-Show 4-Exit
Choice: 1
Item: Pen
1-Add 2-Delete 3-Show 4-Exit
Choice: 1
Item: Book
1-Add 2-Delete 3-Show 4-Exit
Choice: 2
Item to delete: Pencil
Not in list
1-Add 2-Delete 3-Show 4-Exit
Choice: 3
List: ['Pen', 'Book']
1-Add 2-Delete 3-Show 4-Exit
Choice: 4
Summary & practice
- Nested list = list of lists; access with
L[i][j]. b = ais an alias; copy witha[:],list(a),a.copy().- Functions can modify a list passed to them.
- Practise searching, counting, removing duplicates, rotating.
✅ Practice
1) Find the sum of each column of a 3 × 3 matrix. 2) Move all zeros of a list to the end: [0, 5, 0, 3, 8] → [5, 3, 8, 0, 0]. 3) Find common elements of two lists.
Frequently Asked Questions
Does b = a copy a list?
No. It only creates another name (alias) for the same list. Use a[:], list(a) or a.copy() to make a real copy.
How do I access an element of a nested list?
Use two indexes: L[row][column]. For example marks[1][2] gives the third item of the second row.
If a function changes a list passed to it, does the original change?
Yes, if the function modifies the list in place (e.g. L[i] = x or L.append). If the function only re-assigns the parameter to a new list, the original is not affected.
