Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

    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.

  2. 2

    Print leaving_colleague.

  3. 3

    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'].

Back

7/12

  1. 1. Introduction to Lists
  2. 2. Creating Lists
  3. 3. Accessing List Elements
  4. 4. Changing List Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: append()
  7. 7. Removing Elements: pop()
  8. 8. Removing by Value: remove()
  9. 9. Searching a List: in
  10. 10. Nested Lists
  11. 11. Characters of a Text
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.