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.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python Lists

  1. What is a list
  2. Extracting elements from a list
  3. Removing an element
  4. Adding elements
  5. How to count occurrences in a list
  6. How to search for an element in a list
  7. Sorting a list
  8. Reversing the order of a list
  9. List comprehension
  10. Nesting list
  11. How to convert a tuple into a list