Lesson 34 +10 XP

Lists

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

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:
mixed = [1, "two", 3.0, True]

Access items

Indexing starts at 0. Negative indexes count from the end.

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

Length

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

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.