←
Class 11 Computer Science
9. Lists in Python · 9 / 11
⌕
Chapter 9 of 11

9. Lists in Python

13 sections · 6,501 words

About this chapter

234 words · 1 min read

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

492 words · 2 min read

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.

tools = [ ... ]'pen''ruler''eraser''clip'One list. Four elements. Order is kept.
A list is a row of boxes under one name. Order is left to right.

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.

Python
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)

Output
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 descriptionPython exampleTypes 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.

Lists let a program keep a growing set of values under one name.

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.

Watch out: Do not use {} or () for lists. Lists use square brackets [].

⚡ Quick Check Flashcards4 questions
Question 1
What symbols surround a Python list?
Try answering before revealing!
Question 2
Can one list store numbers and text together?
Try answering before revealing!
Question 3
How do you write an empty list?
Try answering before revealing!
Question 4
What separates elements in a list?
Try answering before revealing!

9.2 Accessing elements with indices

478 words · 2 min read

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.
Forward index (left to right)0123'cat''dog''fox''owl'-4-3-2-1Backward index (right to left)
Two-way indexing. Forward counts from 0. Backward counts from -1.

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 4−1=34 - 1 = 3.

You may write an expression in the brackets.

Python works it out first. Then it uses that integer as the index.

Python
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))

Output
animals: ['cat', 'dog', 'fox', 'owl']
animals[0]: cat
animals[2]: fox
animals[-1]: owl
animals[-4]: cat
animals[1 + 2]: owl
len(animals): 4

A missing index raises an IndexError.

A list of 4 items has no index 4. Last forward index is 3.

Python
animals = ["cat", "dog", "fox", "owl"]
try:
    print(animals[9])
except IndexError as error:
    print("Caught error:", error)

Output
Caught error: list index out of range
Index 0 is the first item. People who count from 1 often miss this.

The 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.

Watch out: Python indices start at 0, not 1. The first item is always index 0.

⚡ Quick Check Flashcards4 questions
Question 1
What is the forward index of the first item?
Try answering before revealing!
Question 2
What does index -1 return?
Try answering before revealing!
Question 3
What happens if you ask for index 10 in a list of 4 items?
Try answering before revealing!
Question 4
A list has length 6. What is the last forward index?
Try answering before revealing!

9.3 Lists are mutable

334 words · 2 min read

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.

Python
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)

Output
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.

Python
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)

Output
Basket contents: ['pencil', 'eraser']
Same memory identity? True
Same id means the same list object, not a new list.

Given 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.

Watch out: You cannot add a new item with items[len(items)] = 10. That raises IndexError. Use .append() to add.

⚡ Quick Check Flashcards4 questions
Question 1
What does mutable mean?
Try answering before revealing!
Question 2
Are strings mutable or immutable?
Try answering before revealing!
Question 3
Are lists mutable or immutable?
Try answering before revealing!
Question 4
Does changing an element change the list id?
Try answering before revealing!

9.4 List operations: joining, repeating, searching and slicing

657 words · 3 min read

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.

Python
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)

Output
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 list

To 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.

Python
>>> [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"]
True
Python
mark = ["*"]
print("mark * 5:", mark * 5)
zeros = [0] * 4
print("zeros:", zeros)

Output
mark * 5: ['*', '*', '*', '*', '*']
zeros: [0, 0, 0, 0]

in asks if a value is present.

It returns True or False.

not in is the opposite.

Python
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)

Output
Earth in planets: True
Jupiter in planets: False
Pluto not in planets: True

Slicing 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.
0123456abcdefgwindow: start 2, stop 5letters[2:5]Keeps 2, 3, 4. Stops before 5.Result: ['c', 'd', 'e']
A slice window. Start is kept. Stop is left out.

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].
Python
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])

Output
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.

The stop index is a fence. The item on the fence is not taken.

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.

Watch out: The stop index is exclusive. my_list[0:3] keeps 0, 1 and 2. It does not keep 3.

⚡ Quick Check Flashcards4 questions
Question 1
What happens if you add a list to an integer with +?
Try answering before revealing!
Question 2
What is [1, 2] * 3?
Try answering before revealing!
Question 3
Does in return a number or a boolean?
Try answering before revealing!
Question 4
What does my_list[::-1] do?
Try answering before revealing!

9.5 Traversing a list with loops

526 words · 2 min read

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.

Python
tools = ["pen", "ruler", "eraser"]
for tool in tools:
    print("Tool:", tool)

Output
Tool: pen
Tool: ruler
Tool: eraser

Sometimes 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].

Python
scores = [75, 88, 92]
for i in range(len(scores)):
    print("Index", i, "has score", scores[i])

Output
Index 0 has score 75
Index 1 has score 88
Index 2 has score 92

Set i = 0 before the loop.

Test i < len(my_list).

Do not forget i += 1 inside.

Python
colours = ["red", "green", "blue"]
i = 0
while i < len(colours):
    print("Colour at", i, "is", colours[i])
    i += 1

Output
Colour 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.

Python
numbers = [2, 4, 6, 8]
print("Original:", numbers)
for i in range(len(numbers)):
    numbers[i] = numbers[i] * 10
print("Modified:", numbers)

Output
Original: [2, 4, 6, 8]
Modified: [20, 40, 60, 80]

After the loop the items are 20, 40, 60 and 80.

RoundiOld valueNew value
10220
21440
32660
43880

How to read the table. One row is one round. The last column is written into the list.

Need the index? Use range(len(...)). Need only the value? Loop on 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.

Watch out: Writing for x in my_list: x = x * 2 does not change the list. Assign to my_list[i] to update an item.

⚡ Quick Check Flashcards4 questions
Question 1
What does traversing a list mean?
Try answering before revealing!
Question 2
Which function counts items for an index loop?
Try answering before revealing!
Question 3
Which loop style lets you change items?
Try answering before revealing!
Question 4
What if you forget i += 1 in a while walk?
Try answering before revealing!

9.6 List methods and built-in functions

681 words · 3 min read

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.
CallChanges 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.
Python
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)

Output
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 [].
Python
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)

Output
pop() returned: d list: ['a', 'b', 'c', 'b']
After remove('b'): ['a', 'c', 'b']
After del letters[0]: ['c', 'b']
After clear(): []

ToolWhat 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.

Python
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)

Output
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]
If a method returns None, do not assign that result back to the list name.

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.

Watch out: In-place methods like .sort(), .reverse() and .append() return None. Never write my_list = my_list.sort(), or the name becomes None.

⚡ Quick Check Flashcards4 questions
Question 1
What does my_list.pop() return with no index?
Try answering before revealing!
Question 2
How do pop() and remove() differ?
Try answering before revealing!
Question 3
What if remove() cannot find the value?
Try answering before revealing!
Question 4
Does sorted() change the original list?
Try answering before revealing!

9.7 Nested lists

413 words · 2 min read

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.

Column 0Column 1Column 2Row 0grid[0][0]grid[0][1]grid[0][2]Row 1grid[1][0]grid[1][1]grid[1][2]Row 2grid[2][0]grid[2][1]grid[2][2]
A nested list is a grid. First index is the row. Second index is the column.

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).
Python
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])

Output
Row 0:                 ['Student A', 85, 90]
Student A first score:  85
Student B second score: 88

Use two loops to visit every cell.

The outer loop walks rows. The inner loop walks items in a row.

Python
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
for row in matrix:
    for val in row:
        print(val, end=" ")
    print()

Output
1 2 3 
4 5 6 
7 8 9
One pair of brackets is a row. Two pairs pick one cell.

Given 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.

Watch out: Do not write matrix[1, 2]. A Python list needs two pairs: matrix[1][2].

⚡ Quick Check Flashcards4 questions
Question 1
What is a nested list?
Try answering before revealing!
Question 2
In table[2][1], which number is the row?
Try answering before revealing!
Question 3
How do you count rows in grid?
Try answering before revealing!
Question 4
What does table[0] return?
Try answering before revealing!

9.8 Copying lists and aliasing

432 words · 2 min read

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.

Aliasing (b = a)list_alist_b[10, 20]Both names share 1 listCopying (b = a[:])list_clist_d[10, 20][10, 20]Two separate lists
Aliasing shares one list. Copying makes a second list.

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.

Python
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)

Output
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 copy then copy.copy(original).

Then id(copy_list) == id(original) is False.

The copy has its own memory.

Python
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)

Output
clone1 is original? False
Same id? False
Original list: [1, 2, 3]
Clone1 list:   [1, 2, 3, 99]
Need a backup you can edit? Slice it. Do not assign the name.

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.

Watch out: Writing list2 = list1 does not copy. A change through list2 also changes list1.

⚡ Quick Check Flashcards4 questions
Question 1
What is an alias?
Try answering before revealing!
Question 2
If a = [5, 6] and b = a, what is id(a) == id(b)?
Try answering before revealing!
Question 3
Name two ways to copy lst.
Try answering before revealing!
Question 4
If you append to an independent clone, does the original change?
Try answering before revealing!

9.9 Passing lists to functions

479 words · 2 min read

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.

Python
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)

Output
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.

Python
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)

Output
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]
Caller holds the listFunction gets the same objectIn-place edit: caller sees itName rebound: caller does not
In-place change reaches the caller. Rebinding a name does not.

How to read the figure. Follow the four boxes. The split is edit versus new list.

Want the function to keep the original safe? Pass 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.

Watch out: Reassigning lst = [] only moves the local name. It does not empty the caller list.

⚡ Quick Check Flashcards4 questions
Question 1
Does Python copy a list when you pass it?
Try answering before revealing!
Question 2
If a function runs lst[0] = 50, does the caller see it?
Try answering before revealing!
Question 3
If a function runs lst = [50, 60], does the caller see it?
Try answering before revealing!
Question 4
How can you pass a list so the function cannot edit the original?
Try answering before revealing!

9.10 Practical list programs

556 words · 3 min read

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().

Python
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)

Output
Scores:  [72, 85, 64, 91, 78]
Total:   390
Count:   5
Average: 78.0

The five scores sum to 72+85+64+91+78=39072 + 85 + 64 + 91 + 78 = 390. The average is 390/5=78390 / 5 = 78.

Start with numbers[0] as the largest so far.

Look at each later number.

If it is bigger, replace the record.

Python
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)

Output
List of values: [34, 88, 12, 95, 67, 43]
Largest value:  95

Linear 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.

Start at index 0Compare list[i] with target valueMatch found? Return index iNo match? Move to index i + 1Reached list end? Report not found
Linear search checks items from left to right.

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.
Python
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))

Output
Position of 7 : 3
Position of 99 : -1

Best case: the target is at index 0. That is 1 comparison.

Worst case: last item, or missing. That is all nn items.

Start largest at numbers[0], never at 0. A list of negatives would break a 0 start.

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.

Watch out: Do not set largest = 0. If every number is negative, 0 is wrong. Start with numbers[0].

⚡ Quick Check Flashcards4 questions
Question 1
How do you find the average of a numeric list?
Try answering before revealing!
Question 2
Why start largest at numbers[0], not 0?
Try answering before revealing!
Question 3
What does linear search return when the target is missing?
Try answering before revealing!
Question 4
In a list of 10 items, what is the most comparisons linear search can make?
Try answering before revealing!

Summary

163 words · 1 min read
  • 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.
Explain each important word in your own words. Then say why the rule works.

Exercises

1,056 words · 5 min read

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.

Python
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?

Python
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?

Python
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?

Python
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().

Python
vals = [40, 10, 30, 20]
res1 = sorted(vals)
print(vals, res1)
res2 = vals.sort()
print(vals, res2)

9.6 What will this script print?

Python
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?

Python
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.

Python
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.

Python
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.

Python
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.

Python
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?

Python
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

  1. 9.1: nums[::-2] prints [60, 40, 20]. Then nums[: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.
  2. 9.2: box_a is [1, 2, [3, 4]] with length 3 because .append() adds its argument as one nested element. box_b is [1, 2, 3, 4] with length 4 because .extend() adds each item of the sequence one by one.
  3. 9.3: It prints 15 35 55 (with a trailing space). The test i % 2 == 0 keeps even indices 0, 2 and 4, which hold 15, 35 and 55.
  4. 9.4: p becomes [1, 2, 6, 7, 8] because del p[2:5] deletes indices 2, 3 and 4 (values 3, 4, 5). q becomes [2, 4, 6, 8] because del q[::2] deletes every other item from index 0 (values 1, 3, 5, 7).
  5. 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 leaves vals unchanged. Then .sort() sorts vals in place and returns None.
  6. 9.6: It prints [99, 6, 7, 8]. The assignment list_y = list_x makes an alias, so both names share one list. Changing list_y also changes list_x.
  7. 9.7: It prints orig: [99, 20, 30], then clone: [10, 20, 30, 40]. Slicing orig[:] makes an independent copy, so later changes do not travel between the two lists.
  8. 9.8: It prints after a: [100, 2, 3], then after b: [100, 2, 3]. func_a changes the shared list in place. func_b only rebinds its local name, so the caller list stays [100, 2, 3].
  9. 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.
  10. 9.10: row = [0] 4 is one list of four zeros. grid = [[0] 3] 3 repeats a reference to the same inner list three times. Setting grid[0][0] = 5 then 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)].
  11. 9.11: Set largest to the bigger of the first two items and second to the smaller. Then walk the rest: if a value is bigger than largest, move largest into second and store the new largest; else if it is bigger than second and not equal to largest, replace second. For this list, largest is 95 and second is 78.
  12. 9.12: Start with an empty list unique. For each item in raw, append it only if it is not already in unique. The result is [4, 2, 7, 9, 1].
  13. 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.
  14. 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.
  15. 9.15: It prints after remove: [10, 30, 20, 40], then popped: 20 list: [10, 30, 40]. remove(20) deletes only the first 20. Then pop(2) removes the item now at index 2, which is the remaining 20.
  16. 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.
Up next
Continue to the next chapter