List methods: sort, insert and pop
A canteen queue is not a list you only read. People join in the middle because their friend saved them a place, the person at the front gets served and leaves, and at closing time somebody wants the names in alphabetical order for the register.
append alone cannot do any of that. Lists carry a set of methods —
functions attached to the list itself — for changing what is already
there.
scores = [45, 12, 78]
scores.insert(1, 33)
print(scores)
[45, 33, 12, 78]
insert puts something in the middle
insert takes two arguments: the index the new item should end up at,
and the item. Everything from that index onwards shuffles one place to
the right. Nothing is overwritten.
queue = ["Ayesha", "Bilal", "Chen"]
queue.insert(0, "Fatima")
print(queue)
['Fatima', 'Ayesha', 'Bilal', 'Chen']
insert(0, ...) is "push in at the front". If you give an index past
the end, insert does not complain — it just puts the item last, the
same as append.
pop takes something out and gives it back
remove deletes by value and hands you nothing. pop deletes by
position and returns the item it removed, which is what you want when
the thing you removed is about to be used.
queue = ["Ayesha", "Bilal", "Chen"]
served = queue.pop()
print(served)
print(queue)
Chen ['Ayesha', 'Bilal']
With no argument, pop takes the last item. Give it an index to take a
particular one — pop(0) serves the front of the queue:
queue = ["Ayesha", "Bilal", "Chen"]
first = queue.pop(0)
print(first)
print(queue)
Ayesha ['Bilal', 'Chen']
sort changes the list itself
sort puts the list in order, smallest first, and returns nothing at
all.
scores = [45, 12, 78, 33]
scores.sort()
print(scores)
[12, 33, 45, 78]
The old order is gone. That is the whole point of sort, but it is also
why the next line catches so many people out:
scores = [45, 12, 78]
result = scores.sort()
print(result)
None
scores.sort() sorted the list and returned None, so result is
nothing. Writing scores = scores.sort() destroys your data — the list
is sorted and then thrown away, and scores becomes None. Call
sort() on its own line, never on the right of an =.
sort takes a reverse argument for largest first:
scores = [45, 12, 78, 33]
scores.sort(reverse=True)
print(scores)
[78, 45, 33, 12]
Strings sort alphabetically, with one genuine trap: capital letters come before every lowercase letter, because Python compares character codes rather than reading the way you do.
names = ["Omar", "ayesha", "Bilal"]
names.sort()
print(names)
['Bilal', 'Omar', 'ayesha']
sorted leaves the original alone
sorted() is a plain function, not a method. It reads your list, builds
a new sorted list, and gives that back. Your list is untouched.
scores = [45, 12, 78, 33]
ranked = sorted(scores)
print(ranked)
print(scores)
[12, 33, 45, 78] [45, 12, 78, 33]
So: scores.sort() when the original order does not matter, and
sorted(scores) when you need a leaderboard on screen but the entry
order preserved underneath. sorted takes reverse=True too.
The shape of the call tells you which is which. A method with a dot in front of it, used on its own line, is usually changing the thing. A function whose result you assign to a name is usually building a new thing.
reverse flips the order in place
reverse behaves like sort — it edits the list and returns None. It
does not sort; it simply turns the list back to front.
stops = ["Saddar", "Gulshan", "Nazimabad"]
stops.reverse()
print(stops)
['Nazimabad', 'Gulshan', 'Saddar']
If you want a reversed copy instead, use the slice from the slicing
lesson: stops[::-1] leaves stops exactly as it
was.
count and index answer questions
Neither of these changes anything. count tells you how many times a
value appears; index tells you where the first one is.
votes = ["chai", "juice", "chai", "water", "chai"]
print(votes.count("chai"))
print(votes.index("juice"))
3 1
index stops at the first match and ignores the rest. If the value is
not in the list at all, it does not return -1 or None — it crashes:
votes = ["chai", "juice", "water"]
print(votes.index("lassi"))
So check first when you are not sure:
votes = ["chai", "juice", "water"]
if "lassi" in votes:
print(votes.index("lassi"))
else:
print("not on the list")
not on the list
b = a does not copy a list
Now the one that produces bug reports that read like witchcraft. You save Monday's canteen menu, assign it to Tuesday, add one dish to Tuesday — and Monday changes as well.
monday = ["chai", "samosa"]
tuesday = monday
tuesday.append("biryani")
print(tuesday)
print(monday)
['chai', 'samosa', 'biryani'] ['chai', 'samosa', 'biryani']
The wrong belief is convincing because it is true for numbers. If you
write a = 5 and then b = a, changing b never touches a. So =
looks like it means "take a copy".
It does not. = means "let this name refer to that object". With
tuesday = monday you did not create a second list; you created a
second name for the one list already sitting in memory. append
then changed that single list, and both names show it, because there is
only one thing to show.
Python will tell you plainly if you ask:
monday = ["chai", "samosa"]
tuesday = monday
print(tuesday is monday)
True
== asks whether two lists hold equal values. is asks whether they
are the same object. Here the answer is yes — one list, two labels.
The reason numbers seem to behave differently is that you never change a
number in place. b = b + 1 builds a new number and re-points b at
it. Lists have methods that genuinely modify the object, so the sharing
becomes visible.
Copying properly
To get a second, independent list, ask for one. Any of these three work, and they do the same job:
monday = ["chai", "samosa"]
tuesday = monday.copy()
tuesday.append("biryani")
print(monday)
print(tuesday)
['chai', 'samosa'] ['chai', 'samosa', 'biryani']
monday[:] is the slice version and list(monday) is the function
version. copy() says what it means, so prefer it.
The habit worth building: any time you are about to hand a list to another part of your program that might change it, and you still need the original, copy it at the door. It costs one word and saves the kind of bug where the numbers are wrong and nothing in the code looks wrong.
More on this: the lists lesson for append and
remove, the slicing lesson for [:] and [::-1],
and the loops lesson for walking a list you have just
sorted.
Prefer learning with a teacher?
WasiLearn Academy runs small-group classes covering this material, online and in Karachi.
See the classes