Arrays and Lists

A review of the two ways each language keeps items in a row: a fixed-size array and a list that grows, reading and changing an item by its index, and when to use each.

Novice · C# · Java · Python · JavaScript · TypeScript · Updated

By

After this lesson you can

  • Create a fixed-size array and a growing list, and read or change an item by its index
  • Tell when to use a fixed-size array and when to use a growing list

Key takeaways

  • An array holds a fixed number of items, set when it's made. Each item is reached by its index, starting at 0.
  • A list grows as you add to it. C# calls it List, Java ArrayList, Python list, and JavaScript and TypeScript Array.
  • Python and JavaScript have no separate fixed-size array in everyday code; their list does both jobs.
  • Use a fixed-size array when the count never changes, and a growing list when items come and go.

The snack stand has exactly four price tags on its sign: that number never changes. Its list of snacks does change: next month it adds popcorn. Those are the two ways programs keep items in a row: a fixed-size array, for a count that never changes, and a growing list, for items that come and go. Every language in this course has both, though two of them use one tool for both jobs.

A fixed-size array

An array holds a set number of items side by side, like the numbered cubbies in Why "Play Track 750,000" Is Instant and "Find Golden Hour" Isn't: Memory as Mailboxes. You choose the size when you make it, and it stays that size. Each item is reached by its index, starting at 0, in one step. You can read an item by its index, or put a new value there.

A growing list

A growing list starts with any number of items and grows when you add one. Underneath, it's still an array: when it fills up, the language quietly moves everything into a bigger one. Module 2 opens that up, and its textbook name, a dynamic array. For now, the names to know:

Language Fixed-size array Growing list
C# int[] List<string>
Java int[] ArrayList<String> (used through List<String>)
Python (none in everyday code) list
JavaScript (none in everyday code) Array, written [ ]
TypeScript (none in everyday code) Array, written string[]

Python's list and JavaScript's Array grow whenever you add to them, so they do both jobs. When the course says "array" in Python or JavaScript, it means a list you don't add to.

Both, at the snack stand

The code below keeps the four prices in a fixed-size array and the snacks in a growing list. It reads a price by its index, changes one, adds a snack, and reads the last one.

int[] prices = { 3, 2, 4, 2 };
List<string> snacks = new List<string> { "Pretzel", "Granola Bar", "Trail Mix", "Apple Chips" };

Console.WriteLine(snacks[2] + " costs quot; + prices[2]);

prices[1] = 3;
Console.WriteLine(snacks[1] + " now costs quot; + prices[1]);
Console.WriteLine("Price tags on the sign: " + prices.Length);

snacks.Add("Popcorn");
Console.WriteLine("Snacks after adding one: " + snacks.Count);
Console.WriteLine("The newest snack: " + snacks[snacks.Count - 1]);
Trail Mix costs $4
Granola Bar now costs $3
Price tags on the sign: 4
Snacks after adding one: 5
The newest snack: Popcorn
void main() {
    int[] prices = {3, 2, 4, 2};
    List<String> snacks = new ArrayList<>(List.of("Pretzel", "Granola Bar", "Trail Mix", "Apple Chips"));

    IO.println(snacks.get(2) + " costs quot; + prices[2]);

    prices[1] = 3;
    IO.println(snacks.get(1) + " now costs quot; + prices[1]);
    IO.println("Price tags on the sign: " + prices.length);

    snacks.add("Popcorn");
    IO.println("Snacks after adding one: " + snacks.size());
    IO.println("The newest snack: " + snacks.get(snacks.size() - 1));
}
Trail Mix costs $4
Granola Bar now costs $3
Price tags on the sign: 4
Snacks after adding one: 5
The newest snack: Popcorn
prices = [3, 2, 4, 2]
snacks = ["Pretzel", "Granola Bar", "Trail Mix", "Apple Chips"]

print(f"{snacks[2]} costs ${prices[2]}")

prices[1] = 3
print(f"{snacks[1]} now costs ${prices[1]}")
print(f"Price tags on the sign: {len(prices)}")

snacks.append("Popcorn")
print(f"Snacks after adding one: {len(snacks)}")
print(f"The newest snack: {snacks[-1]}")
Trail Mix costs $4
Granola Bar now costs $3
Price tags on the sign: 4
Snacks after adding one: 5
The newest snack: Popcorn
const prices = [3, 2, 4, 2];
const snacks = ["Pretzel", "Granola Bar", "Trail Mix", "Apple Chips"];

console.log(`${snacks[2]} costs ${prices[2]}`);

prices[1] = 3;
console.log(`${snacks[1]} now costs ${prices[1]}`);
console.log(`Price tags on the sign: ${prices.length}`);

snacks.push("Popcorn");
console.log(`Snacks after adding one: ${snacks.length}`);
console.log(`The newest snack: ${snacks[snacks.length - 1]}`);
Trail Mix costs $4
Granola Bar now costs $3
Price tags on the sign: 4
Snacks after adding one: 5
The newest snack: Popcorn
const prices: number[] = [3, 2, 4, 2];
const snacks: string[] = ["Pretzel", "Granola Bar", "Trail Mix", "Apple Chips"];

console.log(`${snacks[2]} costs ${prices[2]}`);

prices[1] = 3;
console.log(`${snacks[1]} now costs ${prices[1]}`);
console.log(`Price tags on the sign: ${prices.length}`);

snacks.push("Popcorn");
console.log(`Snacks after adding one: ${snacks.length}`);
console.log(`The newest snack: ${snacks[snacks.length - 1]}`);
Trail Mix costs $4
Granola Bar now costs $3
Price tags on the sign: 4
Snacks after adding one: 5
The newest snack: Popcorn

A few things to notice, because they differ between the languages:

  • The size is Length on a C# array and Count on a C# list; length on a Java array and size() on a Java list; len(...) in Python; length in JavaScript and TypeScript.
  • Adding is Add (C#), add (Java), append (Python), push (JavaScript and TypeScript).
  • The last item is at index size − 1, since indexes start at 0. Python also lets you write snacks[-1].
  • Java's List.of(...) makes a list that can't change, so the code wraps it in new ArrayList<>(...) to get one it can add to.

Which one to use

Ask whether the number of items changes:

  • It never changes: the four price tags, the seven days of the week, a chessboard's 64 squares. A fixed-size array says so, and the language stops you from adding a fifth by mistake.
  • Items come and go: the snacks on the menu, a playlist, the people in a line. A growing list.

In everyday code, the growing list is the one you'll use most. The fixed-size array matters in this course because it's what the growing list, and several other structures, are built from.

Try it. Add a second snack, "Lemonade", and print the newest snack again. Then try to print snacks[10]: what does your language do?

Check yourself

2 questions to try on the lesson page.

So what

Arrays and lists are the first data structures you met, even if no one called them that. Module 2 opens up the growing list to show what it does when it fills up, and what that costs.

Key terms

Cheat sheets