Courses / Computer Science I
Programming I

Basic Data Collections

Computer Science I 245 words Free to read

Storing Many Values

A single variable holds one value; a collection holds many. The workhorse is the list (or array) — an ordered sequence of values under one name.

scores = [90, 85, 70, 100]

Each element has a position, its index. A near-universal convention is that indices start at 0: scores[0] is 90, scores[1] is 85, and the last element of a 4-item list is scores[3], not scores[4]. Reading past the end (scores[4] here) is an index-out-of-range error. The number of elements is the list's length (here 4). Lists support adding, removing, and updating elements, and iterating over them with a loop.

A different collection is the dictionary (map, or associative array), which stores key–value pairs and looks up values by key rather than by position:

ages = {"Ana": 30, "Ben": 25}
ages["Ana"]   # 30

A dictionary is unordered by position but gives fast lookup by key. The rule of thumb: use a list when order and position matter and items are accessed by their place in sequence; use a dictionary when you look items up by a meaningful key (a name, an id) rather than a numeric position.

Common pitfall: forgetting that indexing starts at 0. In a list of length n, the valid indices are 0 through n-1; the last element is at index n-1, and accessing index n runs off the end. This off-by-one at the boundary is one of the most common beginner errors.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

11practice questions
2interactive scenes
Start Computer Science I free

Programming I