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. Key takeaways: - A list stores ordered values under one name. - Indexing starts at 0, so the last index is len - 1. - len(...) counts the items. - split() turns a line of text into a list of strings.
Challenge: First and Last