Lesson 34 +10 XP

Lists

A list is an ordered, changeable collection that can hold anything. It's one of Python's four built-in collection types.

Create a list


python
thislist = ["apple", "banana", "cherry"]
print(thislist)

List properties

  • Ordered: items keep the order you add them.
  • Changeable: you can add, remove, and change items.
  • Allow duplicates: the same value can appear twice.
  • Mixed types allowed:

python
mixed = [1, "two", 3.0, True]

Access items

Indexing starts at

  1. Negative indexes count from the end.

python
print(thislist[0])

### apple
print(thislist[-1])

### cherry

Length


python
print(len(thislist))

### 3

The four collection types

  • list: ordered, changeable, allows duplicates.
  • tuple: ordered, unchangeable, allows duplicates.
  • set: unordered, unindexed, no duplicates.
  • dict: key-value pairs, ordered, no duplicate keys.

Lists can hold lists


python
matrix = [[1, 2], [3, 4]]
print(matrix[0][1])

### 2

TL;DR

  • Lists use [ ], are ordered and changeable.
  • Index from 0; negative indexes count from the end.
  • len() gives the length.
  • List is one of four collection types: list, tuple, set, dict.