CodeMIRAI
0 XP

Lists

2 min read 7 runnable examples Quiz included

A list holds an ordered collection of items in square brackets. It is the most-used collection in Python.

Python
fruits = ["apple", "banana", "cherry"]
numbers = [3, 1, 4, 1, 5, 9]
mixed = ["Asha", 21, True, 1.65]
empty = []

print(fruits)
print(len(numbers))
print(mixed)

A list can hold any types, even a mix, and the same value can appear more than once.

Reading items

Lists use the same indexing and slicing as strings:

indexfrom end0"kiwi"-51"fig"-42"plum"-33"pear"-24"lime"-1fruits = ["kiwi", "fig", "plum", "pear", "lime"]fruits[1] and fruits[-4] are the same item: "fig"
Indexes start at 0 at the front and at -1 at the back. A slice like fruits[1:3] takes items 1 and 2: the end is never included.
Python
colours = ["red", "orange", "yellow", "green", "blue"]
print(colours[0])       # first
print(colours[-1])      # last
print(colours[1:3])     # a slice is a new list
print(colours[::-1])    # reversed copy

Changing items

Unlike strings, lists are mutable: you can change them in place.

Python
colours = ["red", "orange", "yellow"]
colours[1] = "purple"
print(colours)

colours[0:2] = ["black", "white"]   # replace a slice
print(colours)

Membership and counting

Python
basket = ["apple", "banana", "apple", "kiwi"]
print("kiwi" in basket)
print("mango" not in basket)
print(basket.count("apple"))
print(basket.index("banana"))

Joining and repeating

Python
a = [1, 2]
b = [3, 4]
print(a + b)
print([0] * 5)

Built-in functions that work on lists

Python
scores = [72, 95, 88, 61]
print(len(scores), sum(scores), min(scores), max(scores))
print(sorted(scores))                  # a new sorted list
print(sum(scores) / len(scores))       # average

A trap: two names, one list

Assigning a list to another variable does not copy it. Both names refer to the same list:

Python
original = [1, 2, 3]
alias = original
alias.append(4)
print(original)        # changed too!

copy = original.copy() # or original[:] or list(original)
copy.append(5)
print(original, copy)

This catches everyone at least once. When you want an independent list, make a copy.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.