Python Reference ยท Lists, Tuples and Ranges
Python list.append() method
Reference for Python list.append(): add one item to the end of a list in place, why it returns None, how it differs from extend(), and the shared-reference trap.
The append() method adds a single item to the end of a list. It changes the list in place and returns None, so there is no new list to assign. Whatever you pass is added as one element, even if it is itself a list.
Appending is the everyday way to build a list one item at a time, usually inside a loop. On average it takes constant time, so it is safe to use for thousands of items.
numbers = [1, 2] numbers.append(3) print(numbers) # [1, 2, 3]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list.append(item)
| Name | Description |
|---|---|
item |
Any object. It becomes the last element of the list. |
Return value: None. The list is modified in place.
Raises: nothing for lists, apart from MemoryError in extreme cases. Appending to a tuple or string fails because they have no append() method (AttributeError).
Usage notes
- Mutates the original. Every name that refers to the same list sees the change, including a list passed into a function.
- Returns
None. Writingnums = nums.append(4)replaces your list withNone. This is the most common mistake. - One item only.
append([3, 4])adds a nested list. To add each element, useextend(),+=or a slice assignment. - Same object, not a copy. Appending a list to itself or reusing one inner list (
grid.append(row)) stores references, so later changes show up everywhere. Create a new object per iteration. - Efficient at the end. Appending is amortized O(1). Inserting at the front is O(n); for queues use
collections.deque.appendleft(). - Alternatives. A list comprehension is often shorter than a loop with
append():[n * n for n in range(1, 6)].lst += [x]also works but creates a temporary list. - Do not append while iterating the same list with
for, because the loop will keep going over the new items and may never end. - Other types:
bytearray.append()takes an integer 0 to 255, andarray.array.append()takes a value of its typecode.
Related
list.extend(),list.insert(),list.pop(),list.remove(),list- Lessons: Lists, List methods