Step 1 of 8 · Reading · ~4 min
Learn
Lists and Tuples
List Basics
A list is a sequence you can edit after you build it. By the end of this lesson you can change a list in place, tell which methods change it and which hand back a new value, and keep two names from silently sharing one list.
In Python Fundamentals you got lists from split() and walked them with for, enumerate and zip, and you saw that a string cannot be edited in place. A list can, and that single difference has consequences.
Editing in place
Assigning to an index or a slice changes the list itself:
The methods that grow and shrink a list:
| call | effect |
|---|---|
s.append(5) | add one item at the end |
s.extend([7, 8]) | add each item of another sequence at the end |
s.insert(1, 40) | put 40 at index 1, shifting the rest right; an index past the end just appends |
s.pop() / s.pop(0) | remove and return the last item / the item at index 0 |
s.remove(60) | remove the first item equal to 60 (ValueError if there is none) |
del s[2] | remove by position |
s.sort() / s.reverse() | reorder in place |
append and extend differ on a list argument: after s = [1], s.append([7, 8]) gives [1, [7, 8]] (one new item, itself a list), while s.extend([7, 8]) gives [1, 7, 8].
Mutators return None
Every method that changes a list in place returns None, not the list:
Built-ins that only look at a list leave it alone and return something: len(s), sum(s), min(s), max(s), s.index(x) (position of the first match), s.count(x), x in s, and sorted(s), which returns a new sorted list. reversed(s) returns a lazy iterator, so wrap it: list(reversed([3, 1, 2])) is [2, 1, 3].
One list, two names
b = a copies the name, not the list:
Variables are labels attached to objects. b = a puts a second label on the same list, so a change through either label is visible through both. list(a), a[:] and a.copy() build a new list holding the same items.
That copy is shallow: the new outer list is separate, but any inner lists are still shared.
The same sharing explains [[0] * 3] * 3: it repeats ONE inner list three times, so grid[0][0] = 9 changes all three rows.
Finally, += and + differ on lists. y += [3] extends the list in place, so every name for it sees the change. y = y + [3] builds a new list and rebinds y, leaving the other names on the old one.
Common mistakes
items = items.sort().sort()returnsNone, so the next" ".join(items)raises TypeError andlen(items)fails. Callitems.sort()on its own line, or usesorted()when you want a value back.- Saving a "backup" with
=.backup = itemsfollowed byitems.append("z")also changesbackup, so restoring it restores nothing. Savelist(items). removeon a missing value.[1, 2].remove(5)raises ValueError. Check5 in sfirst.- Expecting
insertto fail past the end.[1, 2].insert(99, 7)gives[1, 2, 7]; it never raises.
Your exercise
Write a small command interpreter over one list of words, where every edit can be undone. The starter reads the commands and prints for show; the most likely mistake is saving history in a way that later edits quietly rewrite.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…