Skip to content

Index and slice

Every item in a list has its own number — that’s called the index. And yes, just like with range: counting starts at 0.

Inputs (for input())

One value per line — read in order by input().

Output
 
  • fruits[0] — the first item (index 0!)
  • fruits[2] — the third item
  • fruits[-1] — a negative index counts from the end: the last item. A very handy trick!

A colon grabs a range: list[start:stop]. Just like with range, the stop index is not included:

Inputs (for input())

One value per line — read in order by input().

Output
 

[1:3] → indexes 1 and 2 (3 not included). [:2] → from the start up to index 2.

If a list has 4 items, what does fruits[10] give you? IndexError“there’s no such index.” You’ll see this error yourself in a mission soon. 😉

Mission

First and last

+10 XP

Print the first and last team in the table — use a negative index for the last one.

Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

The middle ones

+15 XP

With a slice, print only the middle two fruits in the list.

Inputs (for input())

One value per line — read in order by input().

Output
 
Mission

Catch the error

+15 XP

This program raises an IndexError — run it, read the error, and fix it with an index that exists.

Inputs (for input())

One value per line — read in order by input().

Output
 

Next lesson: a list isn’t frozen — add items, remove them, sort them. Continue →