Lists: Storing Many Values

Lists and Indexing

Part of: Variables, Lists & Procedures

A single variable holds one value. But what if you have 30 test scores or a class roster? Creating score1, score2, ... score30 is hopeless. The answer is a list : one named variable that holds an ordered sequence of values. Creating and indexing In Python you write a list with square brackets: Each value sits at a numbered position called an index . Python lists are zero-indexed : the first element is at index 0, the second at 1, and the last at len(list) - 1. Reaching past the end (here scores[4]) raises an error. Note: AP exam pseudocode lists are one-indexed : LIST[1] is the first element. The idea of ordered, numbered access is identical; only the starting number differs. In runnable Python, always start from 0. Common operations - Access : scores[i] reads the element at index i. - Change : scores[0] = 90 overwrites the first element. - Append : scores.append(64) adds a new element to the end. - Length : len(scores) returns the count of elements. Traversing a list Most list work is a traversal : visiting every element once, usually with a loop: The for s in scores form hands you each value directly. When you need positions instead, use for i in range(len(scores)) and access sco

Challenge: Largest in the List