PythonPython ListsPython list append
How do you add elements using `append()`?
Question 80 of 88 · Updated
On this page
Use list.append(item) to add one item to the end of an existing list. The method changes the original list and returns None.
Example: Add to a shopping list#
PYTHONshopping = ['milk', 'bread'] shopping.append('eggs') print(shopping) # ['milk', 'bread', 'eggs']
The existing items keep their order, and the new item becomes the last element.
Practical use: Collect passing scores#
Start with an empty list and append each score that meets the passing mark.
PYTHONpassed = [] for score in [42, 75, 60, 35]: if score >= 50: passed.append(score) print(passed) # [75, 60]
This pattern is useful when you do not know in advance how many results will match a condition.
Common mistakes#
| Expression | What happens |
|---|---|
items.append('pen') | Adds one item at the end |
items.append([1, 2]) | Adds the entire inner list as one item |
items.append(1, 2) | Raises TypeError: append accepts one argument |
items = items.append('pen') | Changes the original list, then replaces the variable with None |
Use a separate append call for each item, or use extend() when you want to add multiple elements from an iterable. The next lesson compares the two methods.
Remember#
- append() works on empty and nonempty lists and allows duplicate values.
- Other variables referring to the same list also see the change.
- In CPython, appending has amortized O(1) time complexity: usually fast, with occasional resizing.
Try it: Starting with an empty list, what happens when you append [1, 2]? The result is [[1, 2]], not [1, 2].
Official references#
References
- 1.Python Tutorial — More on Listsdocs.python.org
- 2.Mutable sequence typesdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design