Appends an item to a list
Usage
The append()
method adds a single item to the end of the list. This method does not return anything; it modifies the list in place.
Syntax
list.append(item)
Parameter | Condition | Description |
item | Required | An item you want to append to the list |
Examples
# Append 'yellow'
L = ['red', 'green', 'blue']
L.append('yellow')
print(L)
# Prints ['red', 'green', 'blue', 'yellow']
# Append list to a list
L = ['red', 'green', 'blue']
L.append([1,2,3])
print(L)
# Prints ['red', 'green', 'blue', [1, 2, 3]]
# Append tuple to a list
L = ['red', 'green', 'blue']
L.append((1,2,3))
print(L)
# Prints ['red', 'green', 'blue', (1, 2, 3)]
append() vs extend()
append() method treats its argument as a single object.
L = ['red', 'green']
L.append('blue')
print(L)
# Prints ['red', 'green', 'blue']
Use extend() method, if you want to add every item of an iterable to a list.
L = ['red', 'green']
L.extend('blue')
print(L)
# Prints ['red', 'green', 'b', 'l', 'u', 'e']