An ordered, changeable sequence of values: create it, index it, slice it, change it.
# create list
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True]
empty = []
Square brackets, items separated by commas. A list can hold values of any type, even mixed.
# indexing
fruits = ["apple", "banana", "cherry"]
fruits[0]
# ans: "apple"
fruits[-1]
# ans: "cherry"
fruits[1]
# ans: "banana"
Indexes start at 0. Negative indexes (pink) count back from the end: -1 is the last item.
# slice lists
numbers = [0, 1, 2, 3, 4, 5]
numbers[1:4]
# ans: [1, 2, 3]
numbers[:3]
# ans: [0, 1, 2]
numbers[3:]
# ans: [3, 4, 5]
[start:stop] includes start but stops before stop. A missing end means "from the start" or "to the end".
# len() function
fruits = ["apple", "banana", "cherry"]
len(fruits)
# ans: 3
len([])
# ans: 0
# change element
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
# ans: fruits is ["apple", "blueberry", "cherry"]
Lists are mutable: you can replace an item in place.
Predict the result, then press → to check.
# what is the first element?
lst = [10, 20, 30]
lst[0]
# ans: 10
# negative index?
lst = [10, 20, 30]
lst[-1]
# ans: 30
lst[-2]
# ans: 20
# slicing result?
lst = [1, 2, 3, 4, 5]
lst[1:4]
# ans: [2, 3, 4]
# what happens?
lst = [1, 2, 3]
lst[5]
# ans: IndexError
# empty slice?
lst = [1, 2, 3]
lst[5:10]
# ans: []
Unlike indexing, slicing past the end is not an error: you just get fewer (or no) items.
# step in slice?
lst = [0, 1, 2, 3, 4, 5]
lst[::2]
# ans: [0, 2, 4]
# reverse list?
lst = [1, 2, 3]
lst[::-1]
# ans: [3, 2, 1]
# modify with slice?
lst = [1, 2, 3, 4, 5]
lst[1:3] = [20, 30]
# ans: [1, 20, 30, 4, 5]
# nested list access?
matrix = [[1, 2], [3, 4]]
matrix[0][1]
# ans: 2
matrix[0] is the inner list [1, 2]; then [1] picks its second item.
# list concatenation?
lst1 = [1, 2]
lst2 = [3, 4]
lst1 + lst2
# ans: [1, 2, 3, 4]
+ builds a new list; lst1 and lst2 are unchanged.
lst[0] is first, lst[-1] is last; past the end is an IndexError.
lst[a:b] includes a, excludes b; [::-1] reverses.
Assign to an index or a slice to change the list in place.