Course Content
Python Data Structures
Python Data Structures
The append() Method
The append()
method in Python is used to add an element to the end of a list. It's a convenient way to expand a list dynamically without having to create a new one.
Imagine you have a list of cities you want to visit. You've already listed a few, but as your plans evolve, you want to add more cities without replacing the existing ones.
The list currently contains four cities. Now imagine you want to add another city, say "Sydney". Here's how you can do it:
travel_wishlist = ['Paris', 'Tokyo', 'New York', 'Rome'] # Adding a new city to the travel wishlist travel_wishlist.append("Sydney") print(travel_wishlist) # Output: ['Paris', 'Tokyo', 'New York', 'Rome', 'Sydney']
As you can see, "Sydney" has been added to the end of the list without affecting the existing items.
Note
- The list grows by one element every time you use
append()
;- You can append not only strings but also variables, numbers, or even other lists;
- The same logic applies to integers, floats, or any object.
The append()
method allows you to efficiently update your list without recreating it. Additionally, this method is especially practical in for
loops, where you can dynamically build or grow a list by adding elements iteratively based on conditions or computations.
Swipe to show code editor
A friend suggested a new city to visit. Use the append()
method to add a new city (as a nested list) to your travel_wishlist
.
Thanks for your feedback!
The append() Method
The append()
method in Python is used to add an element to the end of a list. It's a convenient way to expand a list dynamically without having to create a new one.
Imagine you have a list of cities you want to visit. You've already listed a few, but as your plans evolve, you want to add more cities without replacing the existing ones.
The list currently contains four cities. Now imagine you want to add another city, say "Sydney". Here's how you can do it:
travel_wishlist = ['Paris', 'Tokyo', 'New York', 'Rome'] # Adding a new city to the travel wishlist travel_wishlist.append("Sydney") print(travel_wishlist) # Output: ['Paris', 'Tokyo', 'New York', 'Rome', 'Sydney']
As you can see, "Sydney" has been added to the end of the list without affecting the existing items.
Note
- The list grows by one element every time you use
append()
;- You can append not only strings but also variables, numbers, or even other lists;
- The same logic applies to integers, floats, or any object.
The append()
method allows you to efficiently update your list without recreating it. Additionally, this method is especially practical in for
loops, where you can dynamically build or grow a list by adding elements iteratively based on conditions or computations.
Swipe to show code editor
A friend suggested a new city to visit. Use the append()
method to add a new city (as a nested list) to your travel_wishlist
.
Thanks for your feedback!