In Python, use list methods append[], extend[], and insert[] to add items [elements] to a list or combine other lists. You can also use the + operator to combine lists, or use slices to insert items at specific positions.
- Add an item to the end: append[]
- Combine lists: extend[], + operator
- Insert an item at specified index: insert[]
- Add another list or tuple at specified index: slice
Add an item to the end: append[]
You can add an item to the end of the list with append[]. If you want to add to positions other than the end, such as the beginning, use insert[] described later.
A list is also added as one item, not combined.
Combine lists: extend[], + operator
You can combine another list or tuple at the end of the list with extend[]. All items are added to the end of the original list.
In the case of a string, each character is added one by one.
It is also possible to combine using the + operator instead of extend[].
In the case of the + operator, a new list is returned. You can also add another list to the existing list with +=.
Insert an item at specified index: insert[]
You can insert an item at the specified index [position] by insert[].
Set the index for the first parameter and the item to be inserted for the second parameter. The index at the beginning is 0 [zero-based indexing]. For negative values, -1 means one before the end.
Like append[], the list is added as a single item, not combined.
Note that insert[] is an O[n] operation and is not efficient. See the official wiki for the computational complexity of various operations on list.
The deque type is provided in the standard library collections module as a type to add an item to the head with O[1]. For example, if you want to treat data as a queue [FIFO], it is more efficient to use deque.
Add another list or tuple at specified index: slice
If you specify a range using slice and assign another list or tuple, all items will be added.
You can also replace the original item. All items in the specified range are replaced.
See the following article for details of slicing.