We can add a single element to a list using the .append()
Python method.
Suppose we have an empty list called garden
:
garden = []
We can add the element "Tomatoes"
by using the .append()
method:
garden.append("Tomatoes") print(garden)
Will output:
['Tomatoes']
We see that garden
now contains "Tomatoes"
!
When we use .append()
on a list that already has elements, our new element is added to the end of the list:
# Create a list garden = ["Tomatoes", "Grapes", "Cauliflower"] # Append a new element garden.append("Green Beans") print(garden)
Will output:
['Tomatoes', 'Grapes', 'Cauliflower', 'Green Beans']
Let’s use the .append()
method to manipulate a list.
Instructions
Jiho works for a gardening store called Petal Power. Jiho keeps a record of orders in a list called orders
.
Use print
to inspect the orders he has received today.
Jiho just received a new order for "tulips"
. Use append
to add this string to orders
.
Another order has come in! Use append
to add "roses"
to orders
.
Use print
to inspect the orders
Jiho has received today.