Sign in

Intro to Computer Science / Unit 8: Lists and Data

8.1 Lists and Indexing

3 practice questionsNot yet reviewed

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, then blue, then 3.
  • colors[1] = "pink" changes an item: lists are mutable.
  • Going past the end (like colors[3]) causes an IndexError.
  • 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?
With nums = [4, 8, 15, 16], what does print(nums[1:3]) display?
What happens when you run items = [1, 2, 3] and then print(items[3])?

Ready for more? Take the Unit 8 test.