Adding Elements to a List in Python
To add elements to the end of a list, you can use two methods:
- The append method for adding a single element.
- The extend method for adding multiple elements.
Note: To use a method, simply call it after the list name, separated by a dot. For example, lista.append or lista.extend.
The append Method
Consider the following list:
anno = [2010, 2011, 2012]
To add a new element to the end of the list, use the append method.
anno.append(2013)
Place the element to be added inside the parentheses.
The new element will be added to the first available position at the end of the list.
After the addition, the list will look like this:
[2010, 2011, 2012, 2013]
The extend Method
To add multiple elements to the end of the list, use the extend method.
Consider the following list:
anno = [2010, 2011, 2012]
First, create a list of the elements you want to add.
extension = [2013, 2014]
Then, add them to the list anno using the extend method.
anno.extend(extension)
After the update, the list anno will be:
[2010, 2011, 2012, 2013, 2014]
And so on.
Inserting Elements into a List
To insert elements at a specific position within a list, use the insert method.
Example
The following list has four elements:
anno = [2010, 2011, 2012, 2013]
To insert an element after the first position:
anno.insert(1, 2008)
After the update, the list becomes:
[2010, 2008, 2011, 2012, 2013]
If the position specified in the insert method is greater than the length of the list, the new element is added to the end of the list.
Example 2
To insert multiple elements within a list, use slicing.
Consider the following list:
anno = [2010, 2011, 2012, 2013]
To add two elements after the first position:
anno[1:1] = [2006, 2007]
After the update, the list becomes:
[2010, 2006, 2007, 2011, 2012, 2013]
And so on.