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

Adding Elements: append()

Lists come with handy tools for common tasks, called methods. A method is a function that belongs to a value. You don't write the value in the parentheses, as with len(students). You write it before the method's name, followed by a dot: students.append("Tom"). Using a function or a method is called calling it.

The method append() adds an element to the end of a list. You write the new element in the parentheses:

car_brands = ["Mercedes", "Cadillac"]
car_brands.append("Volvo")
print(car_brands)
print(len(car_brands))

This prints:

['Mercedes', 'Cadillac', 'Volvo']
3

Read car_brands.append("Volvo") from left to right: for the list car_brands, call the method append(), which adds "Volvo" to its end. The list changes, and so does its length.

This way, you can also build a list step by step, starting from an empty list:

todo = []
todo.append("Buy milk")
todo.append("Walk the dog")
print(todo)

This prints:

['Buy milk', 'Walk the dog']

Method names are case-sensitive, just like variable names. If you write car_brands.Append("Volvo"), the program stops with AttributeError: 'list' object has no attribute 'Append'. Did you mean: 'append'? An attribute is anything that belongs to a value and is written after a dot. A list has no Append, and Python even suggests the right name.

Instructions

  1. 1

    Ava has joined the team. Add "Ava" to the end of colleagues with the method append().

  2. 2

    Print colleagues. The output should be ['Peter', 'Daniel', 'Lucy', 'Ava'].

Back

6/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.