{ }codelper

Learn › TypeScript

Data · 10

Lists and arrays

Many values in a row: count, first and last, sum, transform all.

A list (array) holds several values in order.
The example below reads some numbers, prints the count, the first and last, and the sum, then doubles every value.

import { readFileSync } from "node:fs";const [n, ...nums]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);console.log(nums.length);console.log(nums[0], nums[nums.length - 1]);console.log(nums.reduce((a, b) => a + b, 0));const doubled: number[] = nums.map((x) => x * 2);console.log(doubled.join(" "));
stdin
5
3 1 4 1 5
stdout
5
3 5
14
6 2 8 2 10

Key points

  • Indexes start at 0, so the last value is at count - 1.
  • There are two kinds: a fixed-size array and a list you can keep adding to.
    Names and methods differ by language.
  • Sums and maximums come from one pass from start to end.
    Some languages write a transformation like "double everything" in one line.
  • b = a is not a copy.
    It puts a second name on the same list, so adding to b changes a too (only a C++ vector is copied on assignment).
  • Reading past the end stops most languages with an error.
    The ones that carry on with a wrong value are the dangerous ones.

How each language writes it

Pythonlist — append, len(nums), last is nums[-1].
Has sum and max; doubling is [x * 2 for x in nums].
Out of range: IndexError
JavaScriptArrays — push, length, last is nums.at(-1).
Sum with reduce, maximum with Math.max(...nums), transform with map.
Out of range quietly gives undefined
TypeScriptSame as JavaScript.
Write the element type, as in number[]
JavaFixed array int[] a = new int[n] (a.length), growable ArrayList<Integer> (add, size(), get(i)).
Sum with Arrays.stream(a).sum() or a loop.
Out of range: ArrayIndexOutOfBoundsException
C#Fixed int[] (Length), growable List<int> (Add, Count).
Last is nums[^1].
LINQ Sum(), Max(), Average(), Select.
Out of range: IndexOutOfRangeException
C++std::vector<int> — push_back, size(), last is back().
Sum with std::accumulate, maximum with std::max_element.
[] does not check the range; at(i) throws
CFix the size in advance, like int a[1000], and keep the count yourself.
Sums, maximums and transforms are all loops.
Reading out of range says nothing
Craykon[ ] — Add, Count (up to 10,000 items), last is nums[nums.Count - 1].
Sums and maximums are loops.
Out of range stops with an error saying the list only has items 0–4

Common mistakes

Starting the maximum at 0

nums = [-3, -1]
best = 0
for x in nums:
    if x > best: best = x
print(best)

→ 0 — every value is negative, so it never changes (the answer is -1)

Start from the first value, nums[0].

Reading out of range does not stopJavaScript · TypeScript · C · C++

const nums = [3, 1, 4];
console.log(nums[3]);
console.log(nums[-1]);

→ undefined twice, with no error. C and C++ [] read whatever is in nearby memory

Check that the index is between 0 and count - 1 before reading.

The average got cut to an integerJava · C# · C · C++

int sum = 14, n = 5;
double avg = sum / n;

→ 2 — 14 / 5 is integer division first (not 2.8)

Convert before dividing: (double)sum / n → 2.8.

How languages differ
Printing a whole list looks different everywhere: Python [3, 1, 4], JavaScript [ 3, 1, 4 ], a Java array a tag like [I@1b6d3586, a C# array System.Int32[].
To print with spaces, use Python print(*nums), JavaScript nums.join(" "), C# string.Join(" ", nums) or a loop in Java; Craykon Console.WriteLine(nums) prints 3 1 4 directly.

Practice