Lists and Indexing

Part of: Programming Lab: Python for CSP

A Row of Values. A list holds several values in order under one name. You write it with square brackets and commas. Each value has a position called an index . Indexing starts at 0, so scores[0] is the first value (90) and scores[2] is the third (72). Counting from zero trips up almost everyone at first, so slow down and count carefully. Length and the Last Item. len(scores) gives the number of items, here 3. Because indexing starts at 0, the last valid index is len(scores) - 1. Asking for scores[3] in a three-item list is an error, since there is no index 3. Building Lists From Input. A line of space-separated values becomes a list with split(). To do math you convert each piece to a number. "90 85 72".split() produces ["90", "85", "72"], a list of strings. Indexing gives you one piece, and int(...) converts it to a number. What usually goes wrong. What you see What caused it How to fix it --- --- --- IndexError: list index out of range The length itself was used as an index, but the last position is one below the length Subtract one from the length to reach the final item The first value is skipped and the second one shows up instead Counting started at one, but positions start a

Challenge: First and Last