Lesson 12 of 30
In progress
List methods that do the work
Add, remove, search, sort and copy list items with the methods you will use every day, and learn why sort() returns None.
A list that can only be read is a record. A list you can add to, search and sort is a tool. These methods are the ones you will reach for in almost every program after this module.
What you will learn
- Add items with
append,extendandinsert. - Remove items with
remove,popandclear. - Sort, reverse and copy without surprising side effects.
Adding items
append adds one item to the end. extend adds every item from another iterable. insert places one item at a position and shifts the rest along.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
tasks.extend(["test", "ship"])
print(tasks)
tasks.insert(1, "plan")
print(tasks)
Press Run to see the output.
The difference between append and extend is the classic mix-up. tasks.append(["test", "ship"]) adds one item that happens to be a list, giving you a nested list. extend unpacks the argument and adds each element. If the output contains ['test', 'ship'] as a single element, you used append by accident.
Removing items
remove deletes the first matching value and raises ValueError when the value is absent. pop removes by index and returns the item, which is how you use a list as a stack. clear empties the list.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
queue.remove("Ravi")
print(queue)
last = queue.pop()
print(last)
print(queue)
queue.clear()
print(queue)
Press Run to see the output.
pop() with no argument takes the last item, which is fast. pop(0) takes the first and shifts everything left, which is slower on a long list but fine for small queues. Use remove when you know the value and pop when you know the position and want the item back. remove raises ValueError when the value is not there, so guard it with in if absence is normal rather than exceptional.
Searching without loops
index returns the position of the first match and raises ValueError if it is missing. count returns how many times a value appears. Both pair well with the in operator when you only need a yes or no.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(votes.count("yes"))
print(votes.index("no"))
print("maybe" in votes)
Press Run to see the output.
Guard index with in when absence is normal, or catch the error when it is exceptional. Calling index inside a loop over a large list turns a fast lookup into a slow one, because each call scans from the start.
Sorting in place and sorting a copy
sort() rearranges the list itself and returns None. sorted() returns a new list and leaves the original alone. reverse() flips the order in place.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
names = ["mei", "Ana", "ravi"]
print(sorted(names))
print(sorted(names, key=str.lower))
print(names)
Press Run to see the output.
Sorting is stable, so items that compare equal keep their original order; that is what makes a two-pass sort by different keys predictable. Strings sort by Unicode order, so capitals come before lowercase. key=str.lower sorts case-insensitively, which is almost always what a person expects from a name list. reverse=True sorts from largest to smallest.
result = scores.sort() is the most common list bug in beginner code. sort() returns None, so result is None, and the next line fails with TypeError: 'NoneType' object is not subscriptable. Use scores.sort() on its own line, or result = sorted(scores) when you want a new list.
Copying before you change
Because sort() mutates, keep an untouched version when you need both orders.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(original)
print(ascending)
print(descending)
Press Run to see the output.
list(original) and original[:] also copy, but they copy only one level. A list of lists shares its inner lists with the copy, so editing copy[0] changes original[0]. Lesson 15 shows how to copy nested data properly.
Build a playlist: start with three songs, insert one at the front, remove one by name, sort the rest alphabetically, then print the playlist and its length. Keep the original insertion order in a second list for comparison.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
playlist.insert(0, "Blinding Lights")
playlist.remove("Believer")
playlist.sort()
print(playlist)
print(len(playlist))
print(original_order)
Press Run to see the output.
original_order is copied before any change. Without the copy, both names would point at the same list and the comparison would prove nothing.
Recap
appendadds one item,extendadds each item,insertadds at a position.removeworks by value,popby position and returns the item.sort()mutates and returnsNone;sorted()returns a new list.
Next, you will store labelled data in dictionaries, where you look values up by name instead of position.
Which is faster, remove() or pop()?
Can I sort a list of dictionaries?
Progress is saved in this browser only. No account, no email.