9. Lists in Python
About this chapter
Big idea: A list stores many items under one name. You can change the items later.
This is an original lesson that follows the Class 11 Computer Science syllabus. Read the key words first. Cover a worked answer and try the steps yourself before you look. For a program, say what it will print before you read the real output.
- Create lists of numbers, strings, mixed types and empty lists.
- Access items with forward indices from 0 and backward indices from -1.
- Explain why lists are mutable while strings are immutable.
- Join, repeat, search and slice lists with Python operators.
- Traverse a list with for loops and while loops.
- Use append, extend, insert, pop, sort and reverse.
- Read nested lists with two indices.
- Tell aliasing apart from a true copy.
- Show how a function can change a list, or fail to.
- Write programs for average, largest value and linear search.
In 1958, John McCarthy created Lisp. Lisp stands for LISt Processing. In Lisp, data and code were both lists. Later languages used fixed-size arrays. Programmers had to resize them by hand. In 1991, Guido van Rossum gave Python a built-in list. It indexes like an array. It also grows and shrinks on its own. A Python list can mix types. That mix of speed and ease is why lists sit at the centre of beginner Python.
9.1 Introduction to lists
A list holds many items under one name.
Think of a pencil case.
Pens, a ruler and an eraser sit together.
They belong to one case.
A list works the same way.
It groups many values into one container.
How to read the figure. Four boxes sit in a row. The name tools points to the whole row. Left is first. Right is last.
A list is an ordered sequence.
Items stay in the order you write them.
Each item is an element.
Write elements in square brackets. Separate them with commas.
- List: an ordered sequence of values in square brackets.
- Element: one item stored in a list.
- Sequence: a collection where order matters.
- Empty list: a list with zero elements, written [].
A string holds only text.
A list can hold any type.
You can store whole numbers. You can store words.
You can mix types in one list.
One list can hold an integer, a float, a string and a boolean.
numbers = [2, 4, 6, 8, 10]
words_list = ["pen", "ruler", "eraser"]
mixed = [101, "Student A", 94.5, True]
empty = []
print("numbers:", numbers)
print("words_list:", words_list)
print("mixed:", mixed)
print("empty:", empty)numbers: [2, 4, 6, 8, 10]
words_list: ['pen', 'ruler', 'eraser']
mixed: [101, 'Student A', 94.5, True]
empty: []An empty list has no elements.
Write it as []. Or call list().
Its length is 0.
Start with it when you will collect items later.
| List description | Python example | Types of elements |
|---|---|---|
| Integer list | [10, 20, 30, 40] | All integers |
| String list | ["red", "green", "blue"] | All strings |
| Mixed list | [1, "two", 3.0, False] | Integer, string, float, boolean |
| Empty list | [] | No elements at all |
How to read the table. The middle column is the Python writing. The right column names the types inside.
A student stores five quiz scores: 18, 20, 15, 19, 22. How is this list written?
Goal. Write one list of five scores.
Rule. Use square brackets. Put commas between items.
Open. Write [.
Items. Write 18, 20, 15, 19, 22.
Close. Write ].
Check. Count five numbers. Order matches the scores.
Result: Result: scores = [18, 20, 15, 19, 22].
Cover the answers. Try each item on paper first.
{} or () for lists. Lists use square brackets [].9.2 Accessing elements with indices
Pick an item by its index in square brackets.
Think of numbered lockers in a row.
You need the locker number to open one.
Each list slot has a number. That number is an index.
Write the list name. Then write the index in square brackets.
The form is my_list[index].
Python numbers a list in two ways.
- Forward indexing: The left item is 0. Next is 1. Last is
len - 1. - Backward indexing: The right item is -1. Next left is -2. First is
-len.
How to read the figure. Look at fox. Above it is 2. Below it is -2. Both names pick the same box.
- Index: the position number of an element.
- Forward indexing: counting from the left, starting at 0.
- Negative indexing: counting from the right, starting at -1.
- IndexError: the error when the index does not exist.
The function len() counts items. For four items, len(items) is 4. The last forward index is .
You may write an expression in the brackets.
Python works it out first. Then it uses that integer as the index.
animals = ["cat", "dog", "fox", "owl"]
print("animals:", animals)
print("animals[0]:", animals[0])
print("animals[2]:", animals[2])
print("animals[-1]:", animals[-1])
print("animals[-4]:", animals[-4])
print("animals[1 + 2]:", animals[1 + 2])
print("len(animals):", len(animals))animals: ['cat', 'dog', 'fox', 'owl']
animals[0]: cat
animals[2]: fox
animals[-1]: owl
animals[-4]: cat
animals[1 + 2]: owl
len(animals): 4A missing index raises an IndexError.
A list of 4 items has no index 4. Last forward index is 3.
animals = ["cat", "dog", "fox", "owl"]
try:
print(animals[9])
except IndexError as error:
print("Caught error:", error)Caught error: list index out of rangeThe list is items = [10, 20, 30, 40, 50]. What are the forward and negative indices of 50?
Goal. Name both indices of the last value.
Count. The list has 5 items.
Forward. Last index is 5 - 1 = 4.
Backward. Last index is always -1.
Check. Both items[4] and items[-1] are 50.
Result: Result: forward index 4, negative index -1.
Pause here. Answer before you scroll to the answers.
9.3 Lists are mutable
You can change a list in place. You cannot change a string that way.
Python types are mutable or immutable.
Mutable means changeable in place.
Immutable means the object cannot change after creation.
A string cannot change one character. A list can.
text[0] = "B" raises a TypeError.
A list allows item assignment: my_list[index] = new_value.
- Mutable: able to change in place after creation.
- Immutable: cannot change after creation.
- Item assignment: replacing the element at an index.
- In-place: changing the same object in memory.
Watch a string fail. Then watch a list succeed.
word = "cold"
try:
word[0] = "h"
except TypeError as error:
print("String cannot change:", type(error).__name__)
colours = ["red", "green", "blue"]
print("Before update:", colours)
colours[1] = "yellow"
print("After update: ", colours)String cannot change: TypeError
Before update: ['red', 'green', 'blue']
After update: ['red', 'yellow', 'blue']The list stays in the same memory slot.
id() reports that identity number.
Change an item. The id() stays the same.
basket = ["pen", "eraser"]
id_before = id(basket)
basket[0] = "pencil"
id_after = id(basket)
print("Basket contents:", basket)
print("Same memory identity?", id_before == id_after)Basket contents: ['pencil', 'eraser']
Same memory identity? TrueGiven scores = [70, 80, 90], change the second score from 80 to 85. What is the list after?
Goal. Replace 80 with 85.
Index. The second item sits at index 1.
Write. scores[1] = 85.
Effect. 80 is replaced in place.
Check. First and last values did not move.
Result: Result: [70, 85, 90].
Write a short answer. Then check the notes below.
items[len(items)] = 10. That raises IndexError. Use .append() to add.9.4 List operations: joining, repeating, searching and slicing
Join lists. Repeat them. Search them. Slice out a piece.
Lists use a few simple operators.
You can join. You can repeat. You can search. You can slice.
The + operator joins two lists end to end.
It makes a new list. The old lists stay the same.
Both sides must be lists. A list plus a string raises TypeError.
list1 = [1, 3, 5]
list2 = [2, 4, 6]
print("list1 + list2:", list1 + list2)
print("list1 unchanged:", list1)
print("list2 unchanged:", list2)
try:
print(list1 + "text")
except TypeError as error:
print("TypeError:", error)list1 + list2: [1, 3, 5, 2, 4, 6]
list1 unchanged: [1, 3, 5]
list2 unchanged: [2, 4, 6]
TypeError: can only concatenate list (not "str") to listTo keep the join, assign it: merged = list1 + list2.
The * operator repeats the items.
It makes a new list of copies.
Try these at the prompt.
>>> [1, 2] * 3
[1, 2, 1, 2, 1, 2]
>>> [1, 3, 5] + [2, 4, 6]
[1, 3, 5, 2, 4, 6]
>>> len([10, 20, 30, 40])
4
>>> "Earth" in ["Mercury", "Venus", "Earth"]
Truemark = ["*"]
print("mark * 5:", mark * 5)
zeros = [0] * 4
print("zeros:", zeros)mark * 5: ['*', '*', '*', '*', '*']
zeros: [0, 0, 0, 0]in asks if a value is present.
It returns True or False.
not in is the opposite.
planets = ["Mercury", "Venus", "Earth", "Mars"]
print("Earth in planets:", "Earth" in planets)
print("Jupiter in planets:", "Jupiter" in planets)
print("Pluto not in planets:", "Pluto" not in planets)Earth in planets: True
Jupiter in planets: False
Pluto not in planets: TrueSlicing takes a sublist.
The form is my_list[start:stop:step].
- start: First index kept. Default is 0.
- stop: First index left out. Default is the end.
- step: Gap between kept items. Default is 1.
- Negative step:
my_list[::-1]reverses the list.
How to read the figure. The window starts at 2. It stops before 5. Boxes c, d and e sit inside. Box f at 5 stays out.
- Concatenation: joining two sequences with +.
- Repetition: duplicating items with *.
- Membership operator: testing with in or not in.
- Slicing: taking a portion with [start:stop:step].
letters = ["a", "b", "c", "d", "e", "f", "g"]
print("letters[2:5]: ", letters[2:5])
print("letters[:3]: ", letters[:3])
print("letters[4:]: ", letters[4:])
print("letters[::2]: ", letters[::2])
print("letters[::-1]: ", letters[::-1])letters[2:5]: ['c', 'd', 'e']
letters[:3]: ['a', 'b', 'c']
letters[4:]: ['e', 'f', 'g']
letters[::2]: ['a', 'c', 'e', 'g']
letters[::-1]: ['g', 'f', 'e', 'd', 'c', 'b', 'a']A slice never raises IndexError.
If a bound goes past the end, Python stops at the end.
Given items = [10, 20, 30, 40, 50, 60], what are items[1:4] and items[::-2]?
Goal. Read two slices.
First. Start at index 1 (20). Stop before 4.
Kept. Indices 1, 2, 3 give [20, 30, 40].
Second. Step -2 walks from the end.
Kept. Index 5 is 60. Index 3 is 40. Index 1 is 20.
Check. Three values, skipping one each time.
Result: Result: [20, 30, 40] and [60, 40, 20].
Say the result out loud. Then read the answers.
my_list[0:3] keeps 0, 1 and 2. It does not keep 3.[1, 2] * 3?in return a number or a boolean?my_list[::-1] do?9.5 Traversing a list with loops
Traversal means visit each item, one by one.
You often need every item.
You may print them. You may add them. You may test each score.
Traversal is that walk from start to end.
Python has three common walks.
Use for item in my_list:.
Each round, item holds the next value.
tools = ["pen", "ruler", "eraser"]
for tool in tools:
print("Tool:", tool)Tool: pen
Tool: ruler
Tool: eraserSometimes you need the index too.
Write for i in range(len(my_list)):.
i runs 0, 1, 2, up to len - 1.
Read the value as my_list[i].
scores = [75, 88, 92]
for i in range(len(scores)):
print("Index", i, "has score", scores[i])Index 0 has score 75
Index 1 has score 88
Index 2 has score 92Set i = 0 before the loop.
Test i < len(my_list).
Do not forget i += 1 inside.
colours = ["red", "green", "blue"]
i = 0
while i < len(colours):
print("Colour at", i, "is", colours[i])
i += 1Colour at 0 is red
Colour at 1 is green
Colour at 2 is blue- Traverse: visit each element in order.
- Iterate: repeat a process for each item.
- Loop variable: the name that holds the current item or index.
To change the list, use Method 2.
for item in my_list: only changes item.
It does not write back into the list.
numbers = [2, 4, 6, 8]
print("Original:", numbers)
for i in range(len(numbers)):
numbers[i] = numbers[i] * 10
print("Modified:", numbers)Original: [2, 4, 6, 8]
Modified: [20, 40, 60, 80]After the loop the items are 20, 40, 60 and 80.
| Round | i | Old value | New value |
|---|---|---|---|
| 1 | 0 | 2 | 20 |
| 2 | 1 | 4 | 40 |
| 3 | 2 | 6 | 60 |
| 4 | 3 | 8 | 80 |
How to read the table. One row is one round. The last column is written into the list.
The scores are [18, 24, 15, 21, 22]. Trace a running total. What is the total after each item?
Goal. Add items one by one.
Start. total = 0.
After 18. 0 + 18 = 18.
After 24. 18 + 24 = 42.
After 15. 42 + 15 = 57.
After 21. 57 + 21 = 78.
After 22. 78 + 22 = 100.
Check. Direct sum is 100.
Result: Result: running totals 18, 42, 57, 78, 100.
Predict first. Then compare with the notes.
for x in my_list: x = x * 2 does not change the list. Assign to my_list[i] to update an item.i += 1 in a while walk?9.6 List methods and built-in functions
Functions inspect a list. Methods can change it.
Python gives two kinds of tools.
A built-in function takes the list as an argument, like len(my_list).
A method is called with a dot, like my_list.append(item).
- Method: a function that belongs to an object.
- Dot notation: the form object.method().
- In-place method: a method that changes the list and returns None.
- Return value: what a call hands back.
| Call | Changes the list? | Returns |
|---|---|---|
| append(x) | Yes. Adds x at the end. | None |
| insert(i, x) | Yes. Puts x at index i. | None |
| extend(seq) | Yes. Adds each item of seq. | None |
| pop(i) | Yes. Removes that item. | The removed item |
| remove(x) | Yes. Removes first x. | None |
| sort() | Yes. Sorts in place. | None |
| sorted(lst) | No. Original stays. | A new sorted list |
| len(lst) | No. | The count |
How to read the table. The middle column is the side effect. The right column is the return. Many methods return None.
- append(x): Adds one element at the end. A list argument becomes one nested item.
- extend(sequence): Adds each item of the sequence.
- insert(i, x): Puts x at index i. Later items shift right.
items = [10, 20]
items.append(30)
print("After append(30): ", items)
items.extend([40, 50])
print("After extend([40, 50]): ", items)
items.insert(1, 15)
print("After insert(1, 15): ", items)After append(30): [10, 20, 30]
After extend([40, 50]): [10, 20, 30, 40, 50]
After insert(1, 15): [10, 15, 20, 30, 40, 50]- pop(i): Removes and returns the item at i. No i means the last item.
- remove(x): Removes the first x. Missing x raises
ValueError. - del: Deletes by position:
del my_list[i]or a slice. - clear(): Empties the list to
[].
letters = ["a", "b", "c", "b", "d"]
removed_last = letters.pop()
print("pop() returned:", removed_last, "list:", letters)
letters.remove("b")
print("After remove('b'):", letters)
del letters[0]
print("After del letters[0]:", letters)
letters.clear()
print("After clear():", letters)pop() returned: d list: ['a', 'b', 'c', 'b']
After remove('b'): ['a', 'c', 'b']
After del letters[0]: ['c', 'b']
After clear(): []| Tool | What it does |
|---|---|
| count(x) | How many times x appears |
| index(x) | Index of first x |
| reverse() | Reverses in place |
| sort() | Sorts in place and returns None |
| sorted() | Returns a new sorted list |
| min() / max() | Smallest or largest element |
| sum() | Sum of numbers |
| len() | Number of elements |
my_list.sort() changes the list. It returns None.
sorted(my_list) leaves the original. It returns a new list.
numbers = [45, 12, 89, 33]
new_list = sorted(numbers)
print("Original after sorted():", numbers)
print("New list from sorted(): ", new_list)
numbers.sort()
print("Original after .sort(): ", numbers)
numbers.sort(reverse=True)
print("Sorted descending: ", numbers)Original after sorted(): [45, 12, 89, 33]
New list from sorted(): [12, 33, 45, 89]
Original after .sort(): [12, 33, 45, 89]
Sorted descending: [89, 45, 33, 12]Start with box = [8, 3]. Trace append, insert and pop. Show the list after each call, and what pop returns.
Start. box is [8, 3].
append(5). Add 5 at the end. Now [8, 3, 5].
insert(1, 9). Put 9 at index 1. 3 and 5 shift right. Now [8, 9, 3, 5].
pop(). Remove the last item. It returns 5. Now [8, 9, 3].
Check. Length is 3. Last value is 3.
Result: Result: after append [8, 3, 5]; after insert [8, 9, 3, 5]; pop returns 5 and leaves [8, 9, 3].
Cover the answers. Try each item on paper first.
.sort(), .reverse() and .append() return None. Never write my_list = my_list.sort(), or the name becomes None.my_list.pop() return with no index?pop() and remove() differ?remove() cannot find the value?sorted() change the original list?9.7 Nested lists
A list may hold another list. That makes rows and columns.
Data often sits in a table.
A mark sheet is a table. A game board is a table.
Python stores that grid as a nested list.
The outer list holds inner lists.
How to read the figure. Pick a row first. Then pick a column. grid[1][2] is row 1, column 2.
- Nested list: a list that contains other lists.
- Two-dimensional list: a list of lists as rows and columns.
- Row index: the first index in grid[row][col].
- Column index: the second index in grid[row][col].
Reach one cell with grid[row][col].
- The first index picks the inner list (the row).
- The second index picks the item in that row (the column).
scorecard = [
["Student A", 85, 90],
["Student B", 78, 88],
["Student C", 92, 95]
]
print("Row 0: ", scorecard[0])
print("Student A first score: ", scorecard[0][1])
print("Student B second score:", scorecard[1][2])Row 0: ['Student A', 85, 90]
Student A first score: 85
Student B second score: 88Use two loops to visit every cell.
The outer loop walks rows. The inner loop walks items in a row.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for val in row:
print(val, end=" ")
print()1 2 3
4 5 6
7 8 9Given matrix = [[10, 20], [30, 40], [50, 60]], what is matrix[2][0], and how many rows are there?
Rows. The outer list has 3 inner lists. len(matrix) is 3.
Row 2. Index 2 is [50, 60].
Column 0. Index 0 of that row is 50.
Check. First index is row. Second index is column.
Result: Result: 3 rows, and matrix[2][0] is 50.
Pause here. Answer before you scroll to the answers.
matrix[1, 2]. A Python list needs two pairs: matrix[1][2].table[2][1], which number is the row?grid?table[0] return?9.8 Copying lists and aliasing
A second name is not a copy.
Start with list1 = [10, 20, 30].
Then write list2 = list1.
That is not a copy.
It is a second name for the same list. That is aliasing.
How to read the figure. Left: two names, one box. A change through either name hits that box. Right: two boxes. A change to one copy leaves the other.
- Aliasing: giving an object a second name.
- Alias: a second name for the same object.
- Clone: an independent copy with its own memory.
- Shallow copy: a new outer list that still holds the same elements.
An alias shares the object.
Change list2[0] = 99. Then list1[0] is 99 too.
list1 = [10, 20, 30]
list2 = list1
print("Same object? id(list1) == id(list2):", id(list1) == id(list2))
list2.append(40)
print("list1 after list2.append:", list1)
print("list2 after list2.append:", list2)Same object? id(list1) == id(list2): True
list1 after list2.append: [10, 20, 30, 40]
list2 after list2.append: [10, 20, 30, 40]Use one of these three ways.
- Slicing:
copy_list = original[:]. - list():
copy_list = list(original). - copy module:
import copythencopy.copy(original).
Then id(copy_list) == id(original) is False.
The copy has its own memory.
import copy
original = [1, 2, 3]
clone1 = original[:]
clone2 = list(original)
clone3 = copy.copy(original)
print("clone1 is original?", original is clone1)
print("Same id?", id(original) == id(clone1))
clone1.append(99)
print("Original list:", original)
print("Clone1 list: ", clone1)clone1 is original? False
Same id? False
Original list: [1, 2, 3]
Clone1 list: [1, 2, 3, 99]Predict left after this: left = [2, 4], right = left, right[0] = 9, right.append(6).
Names. right = left makes an alias.
Same object. Both names share one list.
Index change. right[0] = 9 writes into that list.
append. right.append(6) grows that same list.
Check. left must show both edits.
Result: Result: left is [9, 4, 6].
Write a short answer. Then check the notes below.
list2 = list1 does not copy. A change through list2 also changes list1.a = [5, 6] and b = a, what is id(a) == id(b)?lst.9.9 Passing lists to functions
A function receives the same list object the caller holds.
Python passes an object reference.
The function parameter names the caller list.
Two cases follow.
- Argument: the object passed in a call.
- Parameter: the name inside the function that receives it.
- Pass by reference: the function sees the original object.
- Reassignment: binding a name to a new object with =.
Index assignment or .append() edits the shared list.
The caller sees the change.
id() inside matches the caller list.
def add_bonus(scores):
print("Inside function - same id?", id(scores) == initial_id)
for i in range(len(scores)):
scores[i] += 5
class_scores = [70, 80, 90]
initial_id = id(class_scores)
print("Before function call:", class_scores)
add_bonus(class_scores)
print("After function call: ", class_scores)Before function call: [70, 80, 90]
Inside function - same id? True
After function call: [75, 85, 95]Each score grows by 5: 75, 85, 95.
What if the function writes lst = [1, 2, 3]?
That is reassignment.
The local name now points to a new list.
The caller list is not replaced.
def try_to_reset(scores):
print("Inside before reassignment - same id?", id(scores) == initial_id)
scores = [0, 0, 0]
print("Inside after reassignment - same id?", id(scores) == initial_id)
print("Inside function scores: ", scores)
class_scores = [70, 80, 90]
initial_id = id(class_scores)
print("Before function call:", class_scores)
try_to_reset(class_scores)
print("After function call: ", class_scores)Before function call: [70, 80, 90]
Inside before reassignment - same id? True
Inside after reassignment - same id? False
Inside function scores: [0, 0, 0]
After function call: [70, 80, 90]How to read the figure. Follow the four boxes. The split is edit versus new list.
my_list[:], not my_list.A function runs lst.append(99). Does the caller list change?
Rule. .append() edits in place.
Reference. The parameter names the caller list.
Effect. 99 is added to that list.
Check. This is Case A, not reassignment.
Result: Result: yes. The caller list gains 99 at the end.
Say the result out loud. Then read the answers.
lst = [] only moves the local name. It does not empty the caller list.lst[0] = 50, does the caller see it?lst = [50, 60], does the caller see it?9.10 Practical list programs
Use lists to total, find a largest value, and search.
You can now create, walk, slice and change lists.
Three exam programs use those skills.
Add every item. Then divide by len().
scores = [72, 85, 64, 91, 78]
total = 0
for score in scores:
total += score
count = len(scores)
average = total / count
print("Scores: ", scores)
print("Total: ", total)
print("Count: ", count)
print("Average:", average)Scores: [72, 85, 64, 91, 78]
Total: 390
Count: 5
Average: 78.0The five scores sum to . The average is .
Start with numbers[0] as the largest so far.
Look at each later number.
If it is bigger, replace the record.
values = [34, 88, 12, 95, 67, 43]
largest = values[0]
for v in values:
if v > largest:
largest = v
print("List of values:", values)
print("Largest value: ", largest)List of values: [34, 88, 12, 95, 67, 43]
Largest value: 95Linear search walks from index 0.
It compares each item with the target.
A match returns the index.
No match at the end means not found.
How to read the figure. Each step is one comparison. A match stops early. The end means failure.
- Linear search: check every item in order.
- Sequential search: another name for linear search.
- Target: the value you look for.
- Sentinel / Flag: a marker for whether a test passed.
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
numbers = [14, 45, 23, 7, 56, 31]
target1 = 7
target2 = 99
print("Position of", target1, ":", linear_search(numbers, target1))
print("Position of", target2, ":", linear_search(numbers, target2))Position of 7 : 3
Position of 99 : -1Best case: the target is at index 0. That is 1 comparison.
Worst case: last item, or missing. That is all items.
Trace linear search for target 23 in [14, 45, 23, 7, 56]. How many comparisons?
Compare 1. Index 0 is 14. 14 is not 23.
Compare 2. Index 1 is 45. 45 is not 23.
Compare 3. Index 2 is 23. Match.
Stop. Do not look at 7 or 56.
Result: Result: found at index 2 after 3 comparisons.
Predict first. Then compare with the notes.
largest = 0. If every number is negative, 0 is wrong. Start with numbers[0].largest at numbers[0], not 0?Summary
- A list is an ordered sequence in square brackets, with commas between items.
- Lists are mutable. Strings are not. You can change a list in place.
- Indices start at 0 from the left and at -1 from the right. A bad index raises IndexError.
- Use + to join, * to repeat, in to search, and [start:stop:step] to slice. Stop is left out.
- Walk a list by item, by index with range(len(...)), or with while. Change items only by index.
- append adds one item. extend adds each item. insert places at an index. pop removes by index. remove deletes by value.
- sort() changes the list and returns None. sorted() returns a new list and leaves the original.
- A nested list is a grid. Use grid[row][col].
- b = a aliases one list. Copy with a[:], list(a), or copy.copy(a).
- A function sees the caller list. In-place edits show outside. Rebinding the parameter does not.
Exercises
These questions are new. Show your thinking. For programs, write your answer before you run the code.
9.1 Predict the output of the following statements.
nums = [10, 20, 30, 40, 50, 60]
print(nums[::-2])
print(nums[:3] + nums[3:])9.2 What will box_a and box_b contain after these two operations?
box_a = [1, 2]
box_a.append([3, 4])
box_b = [1, 2]
box_b.extend([3, 4])
print(box_a)
print(box_b)9.3 What will this loop print?
items = [15, 25, 35, 45, 55, 65]
for i in range(len(items)):
if i % 2 == 0:
print(items[i], end=" ")9.4 What are the contents of p and q after these deletions?
p = [1, 2, 3, 4, 5, 6, 7, 8]
del p[2:5]
q = [1, 2, 3, 4, 5, 6, 7, 8]
del q[::2]
print(p)
print(q)9.5 Predict the output of this code about sorted() and .sort().
vals = [40, 10, 30, 20]
res1 = sorted(vals)
print(vals, res1)
res2 = vals.sort()
print(vals, res2)9.6 What will this script print?
list_x = [5, 6, 7]
list_y = list_x
list_y[0] = 99
list_y.append(8)
print(list_x)9.7 What will this script print for orig and clone?
orig = [10, 20, 30]
clone = orig[:]
clone.append(40)
orig[0] = 99
print("orig:", orig)
print("clone:", clone)9.8 Predict the output after these two function calls.
def func_a(lst):
lst[0] = 100
def func_b(lst):
lst = [200, 300]
data = [1, 2, 3]
func_a(data)
print("after a:", data)
func_b(data)
print("after b:", data)9.9 A nested list holds a student record. Write statements for (a) marks in the third subject, (b) the highest mark, (c) the roll number, and (d) changing the name to Student Q.
record = ["Student P", "Roll-12", [82, 90, 75, 88, 95], 86.0]9.10 What is the difference between row = [0] 4 and grid = [[0] 3] * 3 when you later change an element?
9.11 Explain how to find the second largest number in [24, 78, 12, 95, 63, 41] without sorting.
9.12 Write a Python fragment that removes duplicate values from raw = [4, 2, 7, 2, 4, 9, 1, 7] while keeping the first occurrence of each value.
raw = [4, 2, 7, 2, 4, 9, 1, 7]
unique = []
for item in raw:
if item not in unique:
unique.append(item)
print(unique)9.13 How do you find the median of [15, 7, 28, 42, 19] and of [12, 5, 20, 8, 30, 25]?
9.14 In [11, 22, 33, 44, 55, 66, 77, 88, 99, 110], how many comparisons does linear search make to find (a) 11, (b) 66, (c) 110, (d) 50?
9.15 Predict the output of these remove and pop operations.
nums = [10, 20, 30, 20, 40]
nums.remove(20)
print("after remove:", nums)
popped = nums.pop(2)
print("popped:", popped, "list:", nums)9.16 How does this two-pointer loop reverse a list in place, and what does it print?
items = [1, 2, 3, 4, 5]
left = 0
right = len(items) - 1
while left < right:
items[left], items[right] = items[right], items[left]
left += 1
right -= 1
print(items)Answers
- 9.1:
nums[::-2]prints[60, 40, 20]. Thennums[:3] + nums[3:]prints[10, 20, 30, 40, 50, 60]. The reverse step of 2 takes 60, 40 and 20. Concatenating the first three items with the rest rebuilds the original list. - 9.2:
box_ais[1, 2, [3, 4]]with length 3 because.append()adds its argument as one nested element.box_bis[1, 2, 3, 4]with length 4 because.extend()adds each item of the sequence one by one. - 9.3: It prints
15 35 55(with a trailing space). The testi % 2 == 0keeps even indices 0, 2 and 4, which hold 15, 35 and 55. - 9.4:
pbecomes[1, 2, 6, 7, 8]becausedel p[2:5]deletes indices 2, 3 and 4 (values 3, 4, 5).qbecomes[2, 4, 6, 8]becausedel q[::2]deletes every other item from index 0 (values 1, 3, 5, 7). - 9.5: The first print is
[40, 10, 30, 20] [10, 20, 30, 40]. The second print is[10, 20, 30, 40] None.sorted()returns a new list and leavesvalsunchanged. Then.sort()sortsvalsin place and returnsNone. - 9.6: It prints
[99, 6, 7, 8]. The assignmentlist_y = list_xmakes an alias, so both names share one list. Changinglist_yalso changeslist_x. - 9.7: It prints
orig: [99, 20, 30], thenclone: [10, 20, 30, 40]. Slicingorig[:]makes an independent copy, so later changes do not travel between the two lists. - 9.8: It prints
after a: [100, 2, 3], thenafter b: [100, 2, 3].func_achanges the shared list in place.func_bonly rebinds its local name, so the caller list stays[100, 2, 3]. - 9.9: (a)
record[2][2]returns 75. (b)max(record[2])returns 95. (c)record[1]returns Roll-12. (d)record[0] = "Student Q"updates the name. - 9.10:
row = [0] 4is one list of four zeros.grid = [[0] 3] 3repeats a reference to the same inner list three times. Settinggrid[0][0] = 5then shows 5 in every row:[[5, 0, 0], [5, 0, 0], [5, 0, 0]]. Independent rows need a loop such as[[0] 3 for _ in range(3)]. - 9.11: Set
largestto the bigger of the first two items andsecondto the smaller. Then walk the rest: if a value is bigger thanlargest, movelargestintosecondand store the new largest; else if it is bigger thansecondand not equal tolargest, replacesecond. For this list, largest is 95 and second is 78. - 9.12: Start with an empty list
unique. For each item inraw, append it only if it is not already inunique. The result is[4, 2, 7, 9, 1]. - 9.13: Sort first. For the five-item list
[7, 15, 19, 28, 42]the middle index is 2, so the median is 19. For the six-item list[5, 8, 12, 20, 25, 30]the two middle values 12 and 20 average to 16.0. - 9.14: (a) 1 comparison, because 11 is at index 0. (b) 6 comparisons, because 66 is at index 5. (c) 10 comparisons, because 110 is last. (d) 10 comparisons, because 50 is absent and every item is checked.
- 9.15: It prints
after remove: [10, 30, 20, 40], thenpopped: 20 list: [10, 30, 40].remove(20)deletes only the first 20. Thenpop(2)removes the item now at index 2, which is the remaining 20. - 9.16: It prints
[5, 4, 3, 2, 1]. The loop swaps the leftmost and rightmost items, then moves the two indices inward until they meet, so the list is reversed without building a new list.