Posted Jun 11, 2020
•
3 min read
When working with lists in Python, you will often want to add new elements to the list.
The Python list data type has three methods for adding elements:
append()
- appends a single element to the list.extend()
- appends elements of an iterable to the list.insert()
- inserts a single item at a given position of the list.All three methods modify the list in place and return None
.
append()
The append()
method adds a single element to the end of the list .
The syntax of the append()
method is as follows:
list.append(element)
Copy
Where, element
is the element to be added to the list.
Here is an example:characters = ['Tokyo', 'Lisbon', 'Moscow', 'Berlin']
characters.append('Nairobi')
print('Updated list:', characters)
Copy
Updated list: ['Tokyo', 'Lisbon', 'Moscow', 'Berlin', 'Nairobi']
The element
parameter can be an object of any data type:
odd_numbers = [1, 3, 5, 7]
even_numbers = [2, 4, 6]
odd_numbers.append(even_numbers)
print('Updated list:', odd_numbers)
#python #add elements #append #extend