Back to Chapters
Chapter Progress: 0 %0 / 7 Lessons Read
‹›

4. Lists

4.2 Access items: index and slice

Highlights & notes

Select lesson text to highlight it, or tap Add note.

    Bookmarks

    Bookmark a lesson to see it here.

      Every item has a position called an index. The first item is index 0. Negative indexes count from the end: -1 is the last item.

      A slice list[start:end] gives a new list from start up to, but not including, end.

      Example

      Python
      files = ["orders.csv", "users.csv", "events.csv", "logs.csv"]
      print(files[0])
      print(files[-1])
      print(files[1:3])
      print(files[:2])
      print(files[2:])
      Output
      orders.csv
      logs.csv
      ['users.csv', 'events.csv']
      ['orders.csv', 'users.csv']
      ['events.csv', 'logs.csv']
      Must Know:

      Asking for an index that doesn't exist, like files[10], raises IndexError. A slice never errors: files[10:] just gives [].

      Practice in Python

      From scores, print the first score, the last score, and a slice of the middle three scores.

      Expected output
      55
      81
      [72, 90, 64]

      Reference solution
      scores = [55, 72, 90, 64, 81]
      print(scores[0])
      print(scores[-1])
      print(scores[1:4])

      Question 1 · Easy

      x = ["a", "b", "c"]. What is x[1]?

      Question 2 · Medium

      x = [10, 20, 30, 40]. What is x[1:3]?

      Question 3 · Hard

      x = [10, 20, 30]. What is x[-2:]?

      Key takeaways

      list[0] is the first item, list[-1] the last. list[a:b] slices from a up to but not including b.

      Lesson 15 of 67

      Save your progress

      Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.

      Start free Log in
      PreviousAccess items: index and slice
      Save your progress free for 1 month. Start free · Log in