ICS3U Computer Science • Ontario Grade 11

Revision sheet: one-dimensional arrays (ICS3U)

This sheet is not a summary of the arrays chapter of ICS3U, Introduction to Computer Science, Grade 11: you already have your notes.

What the sheet covers

It answers one question only, what makes students lose marks on one-dimensional arrays, and which precise gesture avoids each loss.

Array mistakes come in two kinds: the loud ones, an IndexError that stops the program one cell past the end, and the silent ones, a loop that changes a copy, a second name taken for a copy, two parallel arrays that drift apart. The silent ones are harder to catch, because the program runs and prints something plausible. The code is in Python 3, and every value on this sheet comes from a program that was run.

  • 9 mistakes that cost marks
  • 4 figures
  • 15 min reading
Do the chapter's exercises

The thread of the chapter

Every change to an array goes through a cell, a[i] = value, with i from 0 to len(a) - 1: the length is not an index, a loop variable that holds a value is not a cell, and a second name is not a second array.

Topics covered

  • One-dimensional array
  • Array element
  • Array index
  • Array bounds
  • Zero-based indexing
  • Index out of range error
  • Array declaration
  • Array traversal
  • Reference variable
  • Array copy
  • Parallel arrays
  • Negative index

The essentials

Cells, indices, bounds

  • • A one-dimensional array, a list in Python, is a row of cells under one name; a[i] is the cell of index i.
  • • Indices start at 0: an array of n cells has the indices 0 to n - 1, its bounds. len(a) gives n, which is not an index.
  • • [0] * n creates n cells holding 0, the way a Python program declares an array of a given size; [] has no cell at all.
  • • a[i] = value changes one cell and leaves the others; a[i] on the right of = reads it. The index can be an expression: a[i + 1], a[len(a) - 1].
  • • An index outside the bounds stops the program: IndexError: list index out of range when reading, list assignment index out of range when writing.
80311220374456a[0]a[5] = a[len(a) - 1]a[6]: IndexErrora = [8, 3, 12, 0, 7, 4]: len(a) = 6, indices 0 to 5
The six cells of a carry the indices 0 to 5 below them: the last index is len(a) - 1 = 5, and a seventh cell, a[6], does not exist.

A name refers to an array

  • • A variable holds a reference to its array, an arrow to the cells. b = a copies the arrow: two names, one array.
  • • A change of a cell, b[0] = 1, is seen through every name of the array.
  • • Giving a name a new array, a = [1, 2], changes that name only; the old array keeps its other names.
  • • A copy needs new cells: b = [0] * len(a), then for i in range(len(a)): b[i] = a[i]. In Python, b = a[:] does the same in one step.
  • • for x in a: gives x a copy of each value: assigning to x never changes a cell. Changing a cell needs its index.

When a change shows up in an array that no line touched, look for an earlier b = a.

The rules in table form

Each row reads from left to right: the assumptions, then the result. A red cell is not an answer, it is the finding that the form settles nothing and the instruction to rewrite it. Every case is followed by a worked example.

Creating and reading an array, form by form

Each row was run in Python 3; a is [8, 3, 12, 0, 7, 4] when a row uses it.

CodeCells or indexResult
[0] * 4 4 cells [0, 0, 0, 0]

Example: The way to declare an array of 4 cells before filling it: indices 0 to 3.

[5] * 3 3 cells [5, 5, 5]

Example: The one-cell array [5] repeated 3 times.

[5 * 3] 1 cell [15]

Example: The product 5 × 3 = 15 is computed inside the brackets: one cell holding 15.

len(a) counts the cells 6

Example: len counts the 6 cells; the indices are 0 to 5.

a[len(a) - 1] index 5 4, the last cell

Example: a[6 - 1] = a[5] = 4; in an array of 10 cells the same expression reads a[9].

a[len(a)] index 6 IndexError no such cell

Example: a[6] asks for a seventh cell in an array of 6.

What to do: The last cell is a[len(a) - 1]; a loop over the indices is for i in range(len(a)):.

a[-1] counted from the end 4 in Python

Example: a[-1] is a[6 - 1] = 4 and a[-6] is a[0] = 8 in Python; Java stops with an ArrayIndexOutOfBoundsException.

s = [] then s[0] = 5 no cell at all IndexError no cell to write

Example: An empty list has 0 cells, so it has no cell 0, and an assignment never creates one.

What to do: Create the cells first, s = [0] * 5, or grow the list at its end with s.append(5).

Before you write a line with brackets, ask two questions: how many cells, and which index.

The mistakes that cost marks

These are the errors I correct most often in session. Each one costs marks on a paper, even when the reasoning behind it is right.

1. The length taken as the last index

the whole output: the program stops at that line

What not to write

“a = [8, 3, 12, 0, 7, 4], so the last element is a[len(a)], that is a[6] = 4.”

What to write

“The last element is a[len(a) - 1] = a[5] = 4. a[6] stops the program with an IndexError.”

Why: Indices start at 0, so n cells end at index n - 1; len(a) counts the cells, it does not name one.

2. A traversal that starts at 1

1 to 2 marks: a missing value and a crash

What not to write

“for i in range(1, len(a) + 1): print(a[i]) prints the 6 cells.”

What to write

“It skips a[0], prints 5 values, then stops at i = 6 with an IndexError. The traversal is for i in range(len(a)):, which gives 0 to 5.”

Why: Cells are numbered from 0, and a stop of len(a) + 1 visits one index too many.

3. A for x in a loop meant to change the array

1 to 2 marks on a predicted output

What not to write

“for x in a: x = 0 sets every cell of a to 0.”

What to write

“x receives a copy of each value, and a keeps [8, 3, 12, 0, 7, 4]. Write for i in range(len(a)): a[i] = 0.”

Why: A cell changes through an assignment to a[i]; x is a separate variable that holds a copy.

4. Elements used as indices

the whole question: the program stops at once

What not to write

“for i in a: a[i] = a[i] * 2 doubles each cell.”

What to write

“for i in a gives i the values 8, 3, 12 and so on, not the indices: a[8] stops the program on the first pass. Loop over range(len(a)).”

Why: What the loop gives depends on what follows in: an array gives its values, range(len(a)) gives the indices.

5. b = a taken for a copy

1 to 2 marks, and every later answer built on the wrong copy

What not to write

“backup = a, then a[0] = 99: backup keeps the old value 8.”

What to write

“backup and a name the same array, so backup[0] is 99 too. Copy the cells: backup = [0] * len(a), then backup[i] = a[i] for each i.”

99031122abackup990311228031122abackupbackup = a, then a[0] = 99Copied cell by cell, then a[0] = 99
On the left, two arrows reach one array, so a[0] = 99 shows through backup; on the right, the copy has its own cells and keeps 8.

Why: = copies the reference, not the cells; a copy needs new cells.

6. Parallel arrays changed on one side

1 to 2 marks, and a program that runs with no error

What not to write

“items = ['muffins', 'cookies', 'brownies', 'scones'] and left = [12, 30, 8, 15]: to list the brownies first, swap items[0] and items[2].”

What to write

“Swap left[0] and left[2] too. Swapped alone, items[0] is brownies while left[0] is still 12, the muffins count.”

muffinscookiesbrowniesscones12030182153itemsleftindexBefore: column i is one itembrowniescookiesmuffinsscones12030182153itemsleftindexitems[0] and items[2] swapped alone
Before the swap, each column is one item; after swapping items alone, brownies sits over 12 and muffins over 8, two wrong pairs.

Why: In parallel arrays, one index means one item in every array, so each change is made at the same index in all of them.

7. Writing into an empty list

the whole program: it stops at the first value

What not to write

“s = [], then for i in range(5): s[i] = int(input()).”

What to write

“s = [0] * 5 first: an empty list has no cell 0, and the first assignment stops the program. In Python, s.append(int(input())) also works, since it adds a cell at the end.”

Why: An assignment a[i] = ... changes an existing cell; it never creates one.

8. A number from 1 used as an index

1 to 2 marks: every locker is off by one

What not to write

“Locker numbers go from 1 to 30, so taken[number] = True marks the locker number.”

What to write

“The locker numbered k is at index k - 1: taken[number - 1] = True. With taken[number], locker 1 marks the cell of locker 2, and locker 30 stops the program.”

Why: The numbers people use start at 1 and indices at 0: subtract 1 once, in the line that reaches the cell.

9. A negative index that Python accepts

1 mark, and a wrong result that nothing shows

What not to write

“If 0 is typed by mistake, taken[number - 1] = True stops the program with an error.”

What to write

“In Python, taken[-1] is the last cell: locker 30 is marked and nothing warns you. Test number >= 1 and number <= 30 before using the number.”

Why: Python reads a negative index from the end, so only a test you write catches it; Java stops with an ArrayIndexOutOfBoundsException.

Which method to choose

for x in a, or for i in range(len(a))?

Ask what the loop needs: the values only, or the cells themselves.

  • If the loop only reads the values: prints them, tests them, uses them in a calculation → for x in a: is enough, and it cannot go out of bounds

    Example: for x in a: print(x * 2)

  • If the loop changes cells → for i in range(len(a)): with a[i] = ... in the body

    Example: for i in range(len(a)): a[i] = a[i] + 10

  • If the loop needs the position, or two parallel arrays at once → for i in range(len(a)): and the same i in every array

    Example: print(items[i], left[i])

  • If the loop reads a neighbour, a[i + 1] → stop one index earlier: for i in range(len(a) - 1):

    Example: with 6 cells, i goes from 0 to 4 and a[i + 1] from a[1] to a[5]

  • If the loop goes backwards → for i in range(len(a) - 1, -1, -1): from the last index down to 0

    Example: with 6 cells, range(5, -1, -1) gives 5 down to 0

When in doubt, loop over the indices: it can do everything for x in a does, and change the cells too.

How the answer is expected to be written

A marker ticks steps. Here they are in order, with the concluding sentence expected word for word.

Tracing an array program on a unit test

When to use it: « What is printed? », « What does a hold after line 8? », « Which line causes the error? »

  1. 1 Draw the array as cells with their indices below, from 0 to len(a) - 1.
  2. 2 For each assignment a[i] = ..., compute the index first, then the right side with the cells as they are now, then change that one cell.
  3. 3 For a loop, write one row per pass: the value of i or x, and the cells after the pass.
  4. 4 Before each a[i], check that i is between 0 and len(a) - 1; the first index outside stops the trace with an IndexError at that line.
  5. 5 For b = a, draw one array with two arrows; for b = [0] * n, draw new cells.

Concluding sentence

“Pass 6: i = 6, but a has the indices 0 to 5, so a[6] raises an IndexError on line 3 and line 4 never runs.”

The trap: Writing the final array without the states in between: one wrong cell early makes every later row wrong, and the method earns nothing.

Marking: A common split: 1 mark per correct state of the array, 1 for the output or the error.

Writing a program that fills an array

When to use it: « Write a program that reads n values into an array and ... »

  1. 1 Create the cells before the reads: values = [0] * n.
  2. 2 Fill by index: for i in range(n): values[i] = int(input()).
  3. 3 Process with the loop that fits: for x in values to read, for i in range(n) to change the cells or to pair them with another array.
  4. 4 Trace the program on the smallest entry, n = 1, and on one typical entry.

Concluding sentence

“For the entry 3, then 4, 9 and 1, values = [4, 9, 1], and the backward loop prints 1, 9, 4.”

The trap: Starting from values = [] and assigning values[i]: the first assignment stops the program.

Marking: A common split: 1 mark for the creation, 1 for the filling loop, 1 for the processing, 1 for the output.

Check before you hand in

Five minutes of checking recover more marks than one more problem started in a hurry.

  • Every index inside the bounds

    Each index in your answer lies between 0 and len(a) - 1.

    An array of 8 cells: a[8] in your trace means an IndexError, not a value.

  • One assignment per changed cell

    Point to the a[i] = ... line that changed each cell; a cell with no such line keeps its value.

    for x in a: x = 0 has no a[i] = ... line, so the array is unchanged.

  • Two names or two arrays

    For every b = ..., ask whether new cells were created: [0] * n or a[:] create them, b = a does not.

    b = a, then b[2] = 0: a[2] is 0 too.

  • Same length for parallel arrays

    After every append or swap, check that each parallel array got the same change.

    len(items) == len(left) must still be True.

The typical problem, taken apart

Assigning lockers numbered 1 to 30

A school hallway has 30 lockers, numbered 1 to 30 on their doors. The office stores taken = [False] * 30, where taken[i] is True when the locker numbered i + 1 is assigned. Write the line that assigns a locker from its number, then trace the program below for the numbers 1, 30 and 12.

Python
taken = [False] * 30
for k in range(3):
    number = int(input('Locker number: '))
    taken[number - 1] = True
print(taken[0], taken[11], taken[29], taken[1])

Step 1

The array: [False] * 30 gives 30 cells, indices 0 to 29, all False.

Why

One cell per locker, created before any assignment; len(taken) is 30 and the last index is 29.

Step 2

The line: the locker numbered k is at index k - 1, so taken[number - 1] = True.

Why

Door numbers start at 1 and indices at 0: the subtraction is written once, in the line that reaches the cell.

Step 3

Trace: 1 gives taken[0] = True, 30 gives taken[29] = True, 12 gives taken[11] = True. The last line prints True True True False.

True0False1False2...True11...False28True29123122930......lockerindexAfter the numbers 1, 30 and 12: locker k is the cell k - 1

Why

taken[1], locker 2, was never assigned and keeps False: it shows that no neighbour was marked by mistake.

Step 4

The off-by-one version, taken[number] = True: 1 marks taken[1], the cell of locker 2, and 30 asks for taken[30], which stops the program with an IndexError.

Why

The two bounds, 1 and 30, show the mistake; with a middle number like 12, the wrong version runs with no error and marks locker 13.

Step 5

A number typed by mistake, 0: taken[0 - 1] is taken[-1], the last cell, so locker 30 is marked with no error. The guard comes first: if number >= 1 and number <= 30:.

Why

Python reads a negative index from the end, so only a test you write catches it; Java would stop with an ArrayIndexOutOfBoundsException.

The conclusion, written out

“taken[number - 1] = True assigns the locker number. After 1, 30 and 12, taken[0], taken[29] and taken[11] are True, and the other 27 cells are False.”

The classic mistake on this problem: Testing only the number 12: the version taken[number] runs on it with no error and marks locker 13. The bounds 1 and 30 are the tests that show the mistake.

Learn by heart

  • • Indices from 0 to len(a) - 1; len(a) is never an index.
  • • [0] * n declares n cells; [] has none.
  • • A cell changes through a[i] = ...; x = ... in for x in a changes none.
  • • for x in a reads; for i in range(len(a)) reads and changes.
  • • b = a: two names, one array; a copy needs new cells.
  • • Parallel arrays: one index, one item, the same change in every array.
  • • A number that starts at 1 is at index number - 1.
  • • In Python, a[-1] is the last cell: a wrong index can go unnoticed.

Frequently asked questions

Why do array indices start at 0 in Python and Java?

An index counts the cells that come before the one you want: the first cell has none before it, so its index is 0. An array of n cells therefore has the indices 0 to n minus 1, and asking for index n stops the program with an index error. Python lists and Java arrays both count this way.

What does IndexError: list index out of range mean in Python?

It means the program asked for a cell that does not exist: an index equal to or greater than the length of the list, or any index of an empty list. The usual cause is a loop that goes one step too far, such as a stop of len plus 1, or the length used as the last index. The last valid index is the length minus 1.

Why does b = a not copy a list in Python?

A variable holds a reference to its list, not the cells themselves. b = a copies that reference, so a and b name the same list, and a change made through one is seen through the other. To copy, create new cells, for example a list of zeros of the same length, then copy each value with a loop over the indices, or write b = a[:] in Python.

Why does a for x in list loop not change my list?

Because x receives a copy of each value, one at a time. Assigning a new value to x changes that variable only, never a cell of the list. To change the cells, loop over the indices with for i in range(len(a)) and assign to the cell through its index, for example a[i] = 0.

What are parallel arrays in ICS3U?

Two or more arrays of the same length in which the same index describes the same item: names[i] and marks[i] belong to one student. They let a program keep several facts about each item without records, which come in Grade 12. Every change, an added item or a swap, must be made at the same index in all of them, or the facts drift apart.

Mark this sheet as read or add it to your favourites: a free account, no password, keeps your read sheets and favourites from one visit to the next, tells you which chapter to tackle next and lets you ask for the method or exercise you are missing. Create your space, an email is enough.

Practise it

Corrected exercises: One-dimensional arrays, ICS3U

A method is proved on a paper, not on a sheet. The set for the same chapter takes each of these traps into a problem, with the solution written out step by step.

  • 10 corrected exercises
  • 100 points
  • 150 minutes
Do the exercises
Something missing from this sheet? A method, a trap, an exercise to practise it, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Revision sheet published at www.letuteurscientifique.ca/en/fiches/ics3u-one-dimensional-arrays. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session.

Site by Studio Squalli