Removing Elements: pop()
The opposite of append() is the method pop(): it removes the last element of a list. You don't need to write anything in the parentheses, but you do have to write the parentheses.
Besides changing the list, pop() gives the removed element back to you, so that you can keep working with it. We say that the method returns the element, and the element is its return value. You can store the returned value in a variable:
colors = ["blue", "green", "pink"]
last_color = colors.pop()
print(last_color)
print(colors)This prints:
pink
['blue', 'green']The call colors.pop() removed "pink" from the list and returned it, so it was stored in the variable last_color. If you don't need the removed element, simply write colors.pop() on a line of its own.
With an index in the parentheses, pop() removes the element at that index. The elements after it move one place to the left, so their indexes go down by one:
scores = [12, 7, 30, 18]
first_score = scores.pop(0)
print(first_score)
print(scores)This prints:
12
[7, 30, 18]Now 7 is at index 0. If there is no element at the index you give, the program ends with an IndexError, just as when you read an element.
Not every method returns something. append() only changes the list, so never store its result: after colors = colors.append("red"), the variable colors holds None, Python's value for “nothing”, and the list is gone.
Instructions
Ava's project is finished, and she is leaving the team. Remove the last element of colleagues with pop() and store it in a variable leaving_colleague.
Print leaving_colleague.
Peter is retiring. Remove the first element of colleagues with pop(0) (this time you don't need its value), and print colleagues. The output should end with ['Daniel', 'Lucy'].
Start programming for free
7/12