Adding data to a list after creation is a common operation in Python. The list
class supports this operation using various methods:
append()
- Adds a single element at the end of a list.insert()
- Adds a single element at an arbitrary position in the list.extend()
- Adds all the items from the specified iterable at the end of the list.
Adding a single element at the end of the list
The append method is used to add an element at the end of the list.
append(x)
x |
The element to be added to the list |
append an element to a list
#a list of strings
languages = ['Python', 'Java']
#append an element
languages.append('PHP')
print(languages)
languages.append('C++')
print(languages)
languages.append('Javascript')
print(languages)
Insert an element at an arbitrary position
The insert()
method adds an element at a specified index in the list.
insert(i, x)
i |
The index at which to insert the element |
x |
The element to be inserted |
The method inserts element x
at index i
of the list.
insert an element in the list
#a list of strings
nums = ['one', 'two', 'four', 'six', 'seven', 'eight']
#insert an element at index 0
nums.insert(0, 'zero')
print(nums)
nums.insert(3, 'three')
print(nums)
nums.insert(5, 'five')
print(nums)
nums.insert(9, 'nine')
print(nums)
The insert()
method is efficient when we are working with small or medium size lists. When working with large lists, it can be quite slow due to how the insertion is carried on internally.
Extending a list with an iterable
When we have an iterable object, we can add all of its elements at the end of a list using the extend()
method.
extend(iterable)
iterable |
The iterable(list, tuple, set, range, etc) to extend the list with. |
Extend a list
# a list of strings
languages = ['Python', 'Java', 'C++']
print('before: ', languages)
# a tuple of strings
more_languages = ('PHP', 'Java', 'Ruby', 'Swift')
#extend the list with tuple elements
languages.extend(more_languages)
print('after: ', languages)
List Concatenation
List concatenation is a little different from previous approaches in that it leads to a creation of a new list. We can use this operation to combine multiple lists together into one larger list.
We use the + operator to perform string concatenation.
new_list = list1 + list2 + list3
A new list is created and all the elements of the individual lists are added to the new list in the order of their appearance.
Concatenate lists
#lists of integers
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
new_list = list1 + list2 + list3
print(new_list)