Level 1
0 / 100 XP

Creating lists and indexing

A list stores an ordered collection of values in a single variable. Instead of score1, score2, score3, you keep them all together.

Creating a list

Write the values inside square brackets, separated by commas:

Python
scores = [88, 92, 75, 100] fruits = ["apple", "banana", "cherry"] empty = []

A list can hold numbers, strings, or a mix — and it can be empty.

Indexing: reaching one item

Each item has a position, called its index. Python counts from 0, not 1:

Python
fruits = ["apple", "banana", "cherry"] print(fruits[0]) # apple <- first item print(fruits[1]) # banana print(fruits[2]) # cherry <- third item

The first item is fruits[0]. This trips up everyone at first — just remember Python starts counting at zero.

Negative indexing: counting from the end

A negative index counts backward from the end. -1 is always the last item:

Python
fruits = ["apple", "banana", "cherry"] print(fruits[-1]) # cherry <- last item print(fruits[-2]) # banana

This is handy when you want the last item but don't know how long the list is.

How many items? len()

len() gives you the number of items in a list:

Python
fruits = ["apple", "banana", "cherry"] print(len(fruits)) # 3

Because indexing starts at 0, the last valid index is always len(list) - 1. For a 3-item list that's index 2.

Watch out for out-of-range

Asking for an index that doesn't exist raises an error:

Python
fruits = ["apple", "banana", "cherry"] print(fruits[3]) # IndexError: list index out of range

There is no fruits[3] — the valid indexes are 0, 1, and 2.

Key takeaways

  • A list holds an ordered collection of values: [1, 2, 3]
  • Indexing starts at 0 — the first item is list[0]
  • Negative indexes count from the end — list[-1] is the last item
  • len(list) returns how many items the list has
  • The last valid index is len(list) - 1; going past it raises an IndexError