Adding Elements To a List
The append and insert list methods mutate (change) the original list.
append Examples
The general syntax for this method is:
list_name.append(new_value)append adds one new item to the END of a list. The new item may be of any
data type, including another list.
Example
| |
Console Output
['a', 'b', 'c', 'a']
['a', 'b', 'c', 'a', ['l', 'm', 'n', 'o', 'p']]
Note
To add multiple, separate items to the end of a list:
- Use multiple
appendstatements (possibly in a loop), OR - Use concatenation to add two lists together.
| |
Console Output
['a', 'b', 'c', 0, 1, 2, 3]
['a', 'b', 'c', 0, 1, 2, 3, 'l', 'm', 'n', 'o', 'p']
insert Examples
The general syntax for this method is:
list_name.insert(index, new_value)insert adds new_value at the specified index in the list. The new
element may be of any data type, including another list.
Existing data values that come before index remain unchanged. Data values
at or after index all get shifted further down the list.
Example
languages = ['Python', 'JavaScript', 'Java', 'C#']
languages.insert(2, 'Swift')
print(languages)Output
['Python', 'JavaScript', 'Swift', 'Java', 'C#']