Lists
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
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:
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") # 1Lists are mutable
Unlike strings, lists can be changed in place:
names[1] = "Bea" # replace an itemAdding and removing
| 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.
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
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 unchangedsort() 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:
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:
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:
for name in names:
print(name.upper())
total = 0
for score in scores:
total += scoreRemember 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
"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; andb = ashares,a.copy()copies.
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.
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 backupplaylist = ["Yesterday", "Wonderwall", "Bohemian Rhapsody", "Let It Be"]
# 1. Add songs
playlist.append("Hey Jude")
playlist.insert(0, "Imagine")
# 2. Remove "Wonderwall"
playlist.remove("Wonderwall")
# 3. Count, and check for "Yesterday"
print(len(playlist), "songs") # 5 songs
print("Yesterday" in playlist) # True
# 4. First two songs, last song
print(playlist[:2]) # ['Imagine', 'Yesterday']
print(playlist[-1]) # Hey Jude
# 5. Sorted copy (playlist order unchanged)
print(sorted(playlist))
print(playlist)
# 6. Backup, clear, check the backup
backup = playlist.copy() # NOT backup = playlist
playlist.clear()
print(playlist, len(backup)) # [] 5Summary
- 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,extendadd;remove,pop,del,cleardelete;sortandreversereorder in place.sorted(items)returns a new sorted list;items.sort()changes the list and returns None.b = amakes two names for one list — usea.copy()when you need a separate copy.