CodeBlanks Logo Icon CodeBlanks

Index and slice

Learn access with list[i] and list[a:b].

Index and slice

We access list items by index. Indexes start at 0: fruits[0] is the first item. A slice takes a part: fruits[0:2] gives the first two items.

fruits = ["Apple", "Pear", "Banana"]
print(fruits[0])    # Apple
print(fruits[0:2])  # ['Apple', 'Pear']
print(fruits[-1])   # Banana

A slice is [start:stop]; stop is excluded. Negative indexes count from the end.

Slice forms

Slices come in three forms:

  • fruits[1:3] — from 1 to 3 (3 excluded)
  • fruits[:2] — from start to 2
  • fruits[1:] — from 1 to end

An empty start/stop means the list start/end. This short form is very handy.

Slicing is handy for extracting a sublist; the original list is unchanged.

Slicing is handy for extracting a sublist; the original list is unchanged.

Slicing is handy for extracting a sublist; the original list is unchanged.

Slicing is handy for extracting a sublist; the original list is unchanged.

Practice Print slices

Assign fruits = ["Apple", "Pear", "Banana", "Strawberry"]. Print print(fruits[0:2]) and print(fruits[2:]).

Starter code

main.py
# Use slices

Sample solution

main.py
fruits = ["Apple", "Pear", "Banana", "Strawberry"]
print(fruits[0:2])
print(fruits[2:])

Expected output

['Apple', 'Pear']
['Banana', 'Strawberry']

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In fruits = ["a", "b", "c"], what is fruits[1]?

  • "b" Correct answer
  • "a"
  • "c"
  • 1

Explanation: Index 1 is the second item: 'b'.

2 Complete the slice

Question
fruits = ["Apple", "Pear", "Banana"]
print(fruits[____:2])
Answer
fruits = ["Apple", "Pear", "Banana"]
print(fruits[0:2])

Explanation: fruits[0:2] gives the first two items.

3 Match the slice forms

Term Meaning
[0:2] First two
[:2] Start to 2
[2:] 2 to end
[-1] Last item

All lessons in Beginner