Sub topic 2
Removing, Finding, Sorting, and Looping Through Python Lists
Assume you know variables, functions, methods, for loops, and if statements. A list is mutable, so these operations can change the existing list.
Removing items
Use remove(value) to delete the first matching value. It raises ValueError if the value is absent. Use pop(index) to remove and return an item. With no index, pop() removes the last item. del removes by index or slice, while clear() removes everything.
items = ["pen", "book", "pen", "lamp"]
items.remove("pen") # removes the first "pen"
last = items.pop() # removes and returns "lamp"
del items[0] # removes the item at index 0
items.clear() # removes all remaining items
print(last) # lamp
print(items) # []| Operation | Selects by | Returns a removed value |
|---|---|---|
| `remove(x)` | value | No |
| `pop(i)` | index | Yes |
| `del items[i]` | index or slice | No |
| `clear()` | the whole list | No |
Finding items
Use in for a Boolean membership test. index(value) returns the first matching index and raises ValueError when there is no match. count(value) returns the number of matches.
colors = ["red", "blue", "red"]
print("blue" in colors) # True
print(colors.index("red")) # 0
print(colors.count("red")) # 2Sorting and reversing
sort() changes the list and returns None. sorted() creates a new sorted list. Both accept key and reverse.
words = ["pear", "fig", "banana"]
by_length = sorted(words, key=len)
words.sort(reverse=True)
print(by_length) # ['fig', 'pear', 'banana']
print(words) # ['pear', 'fig', 'banana']Use reverse() to reverse a list in place. It does not sort the values.
Looping through a list
A for loop visits items in order. Use enumerate() when you also need each index.
scores = [72, 91, 85]
for position, score in enumerate(scores):
if score >= 80:
print(position, score)Exercise
Which method should you use to remove and save the last item in tasks?
Show answer
Use last_task = tasks.pop().