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)
copy
x |
The element to be added to the list |
Insert an element at an arbitrary position
The insert()
method adds an element at a specified index in the list.
insert(i, x)
copy
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.
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)
copy
iterable |
The iterable(list, tuple, set, range, etc) to extend the list with. |
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
copy
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.