Growing and Shrinking Lists
A method is a function that belongs to a value. You call it with a dot after the value, like tasks.append("report"). The list methods below change the list itself. They do not create a new list.
| Method | What it changes |
|---|---|
append(value) | Adds one value at the end |
insert(index, value) | Adds a value at an index |
remove(value) | Removes the first matching value |
pop(index) | Removes and returns a value |
sort() | Puts the values in order |
reverse() | Reverses the order of the values |
tasks = ["email", "call"]
tasks.append("report")
tasks.append("backup")
removed = tasks.pop()
tasks.remove("call")
tasks.sort()
print(removed)
print(tasks)
Output:
backup
['email', 'report']
With no index, pop() removes the last value and gives it back to you. Here it removed "backup", and the program saved it in removed. If you give pop an index, it removes the value at that position instead. remove("call") works differently. It looks for the value "call" and deletes the first one it finds.
Methods change the list and return None
numbers = [3, 1, 2]
result = numbers.sort()
print(result)
print(numbers)
print(sorted([9, 7, 8]))
Output:
None
[1, 2, 3]
[7, 8, 9]
sort changed the order inside numbers itself, and it returned None. So if you write numbers = numbers.sort(), numbers becomes None and you lose your list. The sorted function works the other way. It gives back a new sorted list and does not change the original.
In the exercise, add the guests who arrive and remove the one who cancels.