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

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

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

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/12