Intro to Computer Science / Unit 8: Lists and Data
8.1 Lists and Indexing
Notes
A list stores an ordered collection of values in square brackets. Each item has an index starting at 0.
colors = ["red", "green", "blue"]
print(colors[0])
print(colors[-1])
print(len(colors))
- This prints
red, thenblue, then3. colors[1] = "pink"changes an item: lists are mutable.- Going past the end (like
colors[3]) causes anIndexError. - A slice
colors[0:2]gives["red", "green"]and stops before index 2.
Practice
With
nums = [4, 8, 15, 16], what does print(nums[2]) display?Indexes: 4 is 0, 8 is 1, 15 is 2.
With
nums = [4, 8, 15, 16], what does print(nums[1:3]) display?The slice starts at index 1 and stops before index 3.
What happens when you run
items = [1, 2, 3] and then print(items[3])?The valid indexes are 0, 1 and 2.
Ready for more? Take the Unit 8 test.