1. Create and index

A list is an ordered collection of values. You create one with square brackets and commas:

A list can hold any type, and one list can mix types. The elements keep the order you write them in.

Each element has an index: a position counted from 0. The syntax is list[index]:

  • 0 is the first element.
  • A negative index counts from the end: -1 is the last element, -2 the one before it.
  • Asking for an index that does not exist raises IndexError.

When you print a list, strings inside it appear with single quotes: [42, 'hello', 3.14, True].

Coming from JavaScript? A list is a JS array. Negative indexes (items[-1]) work directly instead of items.at(-1), and a list can mix types without holes.

#01

Print a list

Create a list named numbers with the values 1, 2, 3, 4 and 5 using a list literal. Then print the whole list.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Read the first element

Create a list named colors with "red", "green" and "blue". Print the element at index 0.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Read the last element

Create a list named animals with "cat", "dog" and "fox". Print the last element using the negative index -1.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

A mixed list

Create a list named mixed with the values 42, "hello", 3.14 and True, in that order. Print the whole list.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

An empty list

Create an empty list named empty and print it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.