Appending Elements to an Array

Now we will start looking at commands that make working with arrays easier.

We will start with the append() command, which adds an element to the end of an array. It's important to note that the append() command has a slightly different syntax than print() and len().

We will demonstrate its use with an example and then explain the syntax:

carBrands = ["Mercedes", "Skoda"]
carBrands.append("Volvo")
print(carBrands)
# Prints: ['Mercedes', 'Skoda', 'Volvo']

The append() command uses dot notation. Before the dot, we have the array to which we want to add a new element. After the dot comes the append() command, which adds the value in parentheses to the end of the array. In the parentheses is the value "Volvo", which we add to the end of the array.

It sounds complicated, but as you can see, the code is relatively simple.

Instructions

Add a new colleague "Ava" to the colleagues array using the append() method.

Print the value of the variable colleagues.

Start programming for free

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

Or sign up with:

6/10

Appending Elements to an Array | Start Coder