Lesson 5.5
Create a list; index; length
Part 5: Text, lists, stacks and queuesReading, about 5 min4 exercises in this lesson
Java answers can't run on Spine yet. You can still read Java, trace it, and put an answer's lines in order.
A list keeps many values under one name
By the end of this you will be able to make a list with values in it, read one value by its index, and ask how many values the list has.
Three test scores fit in three variables: score1, score2, score3. Thirty scores do not, and a program cannot know in advance how many a class will have. A list keeps many values under one name, in order. Each value has an index, and the index is how you reach it.
Making a list and reading from it
scores = [70, 85, 90] print(scores[0]) print(scores[2])
public static void main(String[] args) {
int[] scores = {70, 85, 90};
System.out.println(scores[0]);
System.out.println(scores[2]);
}When it runs:
70 90
In Python the values go between square brackets. In Java this kind of list is called an array. int[] means "an array of whole numbers", and the values go between curly brackets. An array holds one type of value, and once it is made it always has the same number of values. The next lesson shows a Java list that can grow.
To read one value, write the name of the list and then the index in square brackets. That part is the same in both languages.
Indexes start at 0
The first value is at index 0, the second at index 1, and so on. Characters in a text value are numbered the same way.
| index | 0 | 1 | 2 |
|---|---|---|---|
| value | 70 | 85 | 90 |
So scores[0] is 70 and scores[2] is 90.
A common mistake: counting from 1. scores[1] is the second value, 85, not the first.
How many values
scores = [70, 85, 90] print(len(scores))
public static void main(String[] args) {
int[] scores = {70, 85, 90};
System.out.println(scores.length);
}This prints 3. The length is the number of values, and the indexes stop one short of it: three values use the indexes 0, 1 and 2. So the last value of any list is at index length minus 1, the same as the last character of a text value.
In Java, the length of an array has no round brackets after it: scores.length. The length of a text value does: word.length(). Swap them and the program does not compile.
Reading past the end
Ask for an index that is not there and the program stops with an error.
scores = [70, 85, 90] print(scores[3])
public static void main(String[] args) {
int[] scores = {70, 85, 90};
System.out.println(scores[3]);
}Python stops with IndexError: list index out of range. Java stops with an ArrayIndexOutOfBoundsException. Both mean the same thing: the list has no value at that index.
The usual cause is using the length as an index. A list of 3 values has length 3, and its last index is 2.
In Java, a negative index is an error too. Python counts back from the end instead, so scores[-1] is the last value. Counting back past the first value, as scores[-4] does, is an error in Python too.
Now try it yourself on the questions below.
Exercise 5.5.1 · Trace itTrace: list index
Complete the trace table for this Python code. prices[i] is the value at index i, and len(prices) is the number of values. [4]
Line 1: prices = [4, 9, 2, 7]Line 2: i = 1Line 3: a = prices[i]Line 4: i = len(prices) - 1Line 5: b = prices[i]Line 6: print(a + b)
Fill in one row each time a line changes i, a or b, or prints something. The table already has the right number of rows. In each row, write only what that line changes; you can leave the other cells empty or copy their values down. Write values the way Python shows them: 3 and 3.0 are different, and text goes in quotes. In the output column, write exactly what appears on screen, with no quotes around it.
| Row | i | a | b | output |
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
Exercise 5.5.1 · Trace itTrace: list index (Java)
Complete the trace table for this Java code. prices[i] is the value at index i, and prices.length is the number of values. [4]
Line 1: int[] prices = {4, 9, 2, 7};Line 2: int i = 1;Line 3: int a = prices[i];Line 4: i = prices.length - 1;Line 5: int b = prices[i];Line 6: System.out.println(a + b);
Fill in one row each time a line changes i, a or b, or prints something. The table already has the right number of rows. In each row, write only what that line changes; you can leave the other cells empty or copy their values down. Write values the way Java shows them: 3 and 3.0 are different, and text goes in quotes. In the output column, write exactly what appears on screen, with no quotes around it.
| Row | i | a | b | output |
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
Exercise 5.5.25.5.2 · Write itLast value
Write a function that returns the last value in a list (an array in Java) of whole numbers.
- The list has at least one value.
- Return the value at the last index.
Only the value your function returns is checked.
def last_value(values: list[int]) -> int
Examples
Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.
- last_value([3, 8, 5]) should return 5: the last of three values (rule 2)
- last_value([7]) should return 7: one value is both the first and the last (rule 1)
- last_value([9, 4, 1]) should return 1: the last value is the smallest one (rule 2)
public static int lastValue(int[] values)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.
- lastValue(new int[]{3, 8, 5}) should return 5: the last of three values (rule 2)
- lastValue(new int[]{7}) should return 7: one value is both the first and the last (rule 1)
- lastValue(new int[]{9, 4, 1}) should return 1: the last value is the smallest one (rule 2)
Exercise 5.5.35.5.3 · Write itMiddle value
Write a function that returns the middle value of a list (an array in Java) of whole numbers.
- The list has an odd number of values, and at least one.
- The middle value is the one with the same number of values before it as after it.
- The values are in no particular order. The middle value is about where a value sits in the list, not how big it is.
Only the value your function returns is checked.
def middle_value(values: list[int]) -> int
Examples
Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.
- middle_value([4, 9, 2]) should return 9: one value each side; 9 is in the middle although it is the largest (rule 3)
- middle_value([6]) should return 6: one value: nothing before it and nothing after it (rule 2)
- middle_value([5, 1, 3, 8, 7]) should return 3: two values each side; 3 is neither the largest nor the middle-sized value (rule 3)
public static int middleValue(int[] values)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.
- middleValue(new int[]{4, 9, 2}) should return 9: one value each side; 9 is in the middle although it is the largest (rule 3)
- middleValue(new int[]{6}) should return 6: one value: nothing before it and nothing after it (rule 2)
- middleValue(new int[]{5, 1, 3, 8, 7}) should return 3: two values each side; 3 is neither the largest nor the middle-sized value (rule 3)
Exercise 5.5.45.5.4 · Write itIs it an index?
Write a function that returns whether a whole number is an index of a list (an array in Java) of whole numbers.
- The indexes of a list start at 0 and stop one short of the number of values. A list of 3 values has the indexes 0, 1 and 2.
- Return
Truewhenindexis one of them andFalsewhen it is not (trueandfalsein Java). indexcan be any whole number. A negative number is never an index here.- The list can be empty. An empty list has no indexes.
Only the value your function returns is checked.
def valid_index(values: list[int], index: int) -> bool
Examples
Your function is tested on 10 cases: the 4 examples below, and 6 hidden ones that check the rules above.
- valid_index([3, 8, 5], 0) should return True: index 0, the first one (rule 1)
- valid_index([3, 8, 5], 2) should return True: the last index of three values (rule 1)
- valid_index([3, 8, 5], 3) should return False: the number of values is one past the last index (rule 1)
- valid_index([3, 8, 5], -1) should return False: a negative number (rule 3)
public static boolean validIndex(int[] values, int index)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 10 cases: the 4 examples below, and 6 hidden ones that check the rules above.
- validIndex(new int[]{3, 8, 5}, 0) should return true: index 0, the first one (rule 1)
- validIndex(new int[]{3, 8, 5}, 2) should return true: the last index of three values (rule 1)
- validIndex(new int[]{3, 8, 5}, 3) should return false: the number of values is one past the last index (rule 1)
- validIndex(new int[]{3, 8, 5}, -1) should return false: a negative number (rule 3)