Python List append() Function
The List append()
method adds an item to the end of the list.
Syntax
my_list.append(item)
append() Parameters
Python List append()
method parameters::
Parameter | Condition | Description |
---|---|---|
item | Required | An item you want to append to the list |
append() Return Value
Python List append()
function does not return any value: it modifies the list in place.
Examples
Example 1: Adding an Element to a List with append()
For example, let's append a string to a list:
my_list = ['Tom', 'Ryan', 'David']
my_list.append('Anna')
print(my_list) # Output: ['Tom', 'Ryan', 'David', 'Anna']
output
['Tom', 'Ryan', 'David', 'Anna']
Example 2: Adding List to a List with append()
The append()
method can add a list as an element of another list, resulting in a nested list structure.
my_list = ['Tom', 'Ryan']
my_list.append(['David', 'Anna'])
print(my_list) # Output: ['Tom', 'Ryan', ['David', 'Anna']]
output
['Tom', 'Ryan', ['David', 'Anna']]
Example 3: Adding Tuple to a List with append()
The append()
method can add also a tuple as an element of another list.
my_list = ['Tom', 'Ryan']
my_list.append(('David', 25, 'Anna', 23))
print(my_list) # Output: ['Tom', 'Ryan', ('David', 25, 'Anna', 23)]
output
['Tom', 'Ryan', ('David', 25, 'Anna', 23)]
Example 4: Using append() in a Loop
You can use append()
method in a for loop to add multiple elements to a list.
In the following example, a for loop is used with append()
to add multiple elements to the letters
list:
letters = ['a', 'b', 'c']
for letter in 'def':
letters.append(letter)
print(letters) # Output: ['a', 'b', 'c', 'd', 'e', 'f']
output
['a', 'b', 'c', 'd', 'e', 'f']
Example 5: append() vs extend()
The append()
method treats its argument as a single object.
my_list = ['red', 'green']
my_list.append('blue')
print(my_list) # Output: ['red', 'green', 'blue']
output
['red', 'green', 'blue']
You can use extend()
method if you want to add every item of an iterable to a list.
my_list = ['red', 'green']
my_list.extend('blue')
print(my_list) # Output: ['red', 'green', 'b', 'l', 'u', 'e']
output
['red', 'green', 'b', 'l', 'u', 'e']
If you need to add items of a list (rather than the list itself) to another list, use the extend()
method.