Lists

Topic 1 of 5 in Collections7 min readBeginnerFree course

Overview

Most programs deal with many things at once: a list of tasks, a set of scores, every line of a file. A list stores an ordered collection of values under one name. It’s the most-used collection in Python.

Creating lists

Python
scores = [91, 78, 85]
names = ["Asha", "Ben", "Chen"]
mixed = ["Asha", 29, True]        # any types (but usually one kind per list)
empty = []
letters = list("abc")             # ['a', 'b', 'c']
numbers = list(range(1, 6))       # [1, 2, 3, 4, 5]

Items are separated by commas inside square brackets. Lists can even contain other lists: grid = [[1, 2], [3, 4]], and grid[1][0] is 3.

Reading items: indexing and slicing

Lists use exactly the same positions as strings — starting at 0, negative from the end:

Python
names = ["Asha", "Ben", "Chen", "Dee"]
names[0]       # 'Asha'
names[-1]      # 'Dee'
names[1:3]     # ['Ben', 'Chen'] — a new list
names[::-1]    # ['Dee', 'Chen', 'Ben', 'Asha']
len(names)     # 4
"Ben" in names # True
names.index("Chen")   # 2 — position of a value (ValueError if absent)
names.count("Ben")    # 1

Lists are mutable

Unlike strings, lists can be changed in place:

Python
names[1] = "Bea"          # replace an item

Adding and removing

Changing a list, starting from nums = [4, 1, 7] before each line. nums.append(9) adds to the end, giving [4, 1, 7, 9]. nums.insert(0, 2) adds at a position: [2, 4, 1, 7]. nums.extend([5, 6]) adds several: [4, 1, 7, 5, 6]. nums.remove(1) removes the first matching value: [4, 7]. nums.pop() removes and returns the last item, 7, leaving [4, 1]. nums.sort() sorts in place: [1, 4, 7]. sorted(nums) returns a new sorted list [1, 4, 7] and leaves nums unchanged. nums.reverse() reverses in place: [7, 1, 4].

To… Use
add one item to the end items.append(x)
add at a position items.insert(i, x)
add several items items.extend(other) or items += other
remove by value items.remove(x) — the first match; ValueError if absent
remove by position items.pop(i) — returns the item; pop() takes the last
delete by position or slice del items[i], del items[1:3]
empty the list items.clear()

A common slip: append adds one item, even if that item is a list.

Python
nums = [1, 2]
nums.append([3, 4])    # [1, 2, [3, 4]] — a list inside the list
nums = [1, 2]
nums.extend([3, 4])    # [1, 2, 3, 4]

Sorting

Python
scores = [78, 91, 85]
scores.sort()                 # changes scores: [78, 85, 91]
scores.sort(reverse=True)     # [91, 85, 78]

ordered = sorted(scores)      # NEW list; scores is unchanged

sort() returns None. Writing scores = scores.sort() throws your list away and leaves None — a classic bug. Use sort() when you want to change the list, sorted() when you want a sorted copy. Strings sort alphabetically, with capitals before lower case; Functions as values shows how to sort by any rule.

Handy built-ins for lists of numbers: sum(scores), min(scores), max(scores), and len(scores) — so the average is sum(scores) / len(scores).

The aliasing trap

Remember that variables are names attached to values (Variables)? With a list, that has a big consequence:

Two names, one list. a = [1, 2, 3], then b = a — both names point to the same list object. b.append(4) changes that one list, so print(a) shows [1, 2, 3, 4]. For a real copy use b = a.copy() (or a[:] or list(a)); then b.append(4) leaves a as [1, 2, 3].

Python
a = [1, 2, 3]
b = a           # b is another name for the SAME list
b.append(4)
print(a)        # [1, 2, 3, 4]  — a changed too!

b = a doesn’t copy anything; it attaches a second name. When you need an independent list, copy it:

Python
b = a.copy()    # or a[:] or list(a)

These are shallow copies: a new outer list, but if the items are themselves lists, those inner lists are still shared. For lists of numbers and strings that doesn’t matter; for nested lists, use copy.deepcopy().

You can check whether two names share one object with is: after b = a, a is b is True; after b = a.copy(), it’s False even though a == b.

Lists and loops

Lists and for loops go together:

Python
for name in names:
    print(name.upper())

total = 0
for score in scores:
    total += score

Remember from For loops and range: don’t add or remove items from a list while looping over it. Build a new list instead.

Strings ↔ lists

Python
"tea,coffee,cake".split(",")      # ['tea', 'coffee', 'cake']
"the quick fox".split()           # ['the', 'quick', 'fox'] — split on spaces
", ".join(["tea", "coffee"])      # 'tea, coffee'

split and join are covered fully in String methods.

Remember: lists are ordered and changeable; most list methods change the list in place and return None; and b = a shares, a.copy() copies.

Exercise

A playlist manager

Start from the playlist in the starter and, step by step: (1) add "Hey Jude" to the end and "Imagine" at the start; (2) remove "Wonderwall"; (3) print how many songs there are and whether "Yesterday" is in the playlist; (4) print the first two songs and the last song using slicing and negative indexing; (5) make a sorted copy for display WITHOUT changing the playlist order, and print both; (6) make a backup copy, clear the playlist with .clear(), and show that the backup still has all the songs.

Python
playlist = ["Yesterday", "Wonderwall", "Bohemian Rhapsody", "Let It Be"]

# 1. Add songs

# 2. Remove "Wonderwall"

# 3. Count, and check for "Yesterday"

# 4. First two songs, last song

# 5. Sorted copy (playlist order unchanged)

# 6. Backup, clear, check the backup

Summary

  • A list is an ordered, changeable collection: [1, 2, 3]; it can hold any types and grow or shrink.
  • Index and slice lists like strings: items[0], items[-1], items[1:3].
  • append, insert, extend add; remove, pop, del, clear delete; sort and reverse reorder in place.
  • sorted(items) returns a new sorted list; items.sort() changes the list and returns None.
  • b = a makes two names for one list — use a.copy() when you need a separate copy.