Learn How to Append Items to Python List

In this python 3 tutorial we are going to learn how to append new elements to a python list using python append() function.

Add elements to the end of a list

In python append() method use to append items to a python list. When you append an item to a list, the new item will be added to the end of the python list.

list_name.append("new item")

Example

In this example, we have a python list called languages, which contains a list of programming languages.

languages = ["java", "php", "javascript", "perl"]
print(languages)

Then, we add the new element "python" to the end of the list using append() method.

languages = ["java", "php", "javascript", "perl"]
print(languages)
languages.append("python")
print(languages)

The above code will append python to the languages list. The code will output,

['java', 'php', 'javascript', 'perl']
['java', 'php', 'javascript', 'perl', 'python']

Insert Elements into a list by index position

Instead of appending items to the end of the list, we can use insert() method to add items at any given position, by index number (Remember python list starts with index 0).

Example 1

languages = ["java", "php", "javascript", "perl"]
print(languages)
languages.insert(0, "python")
print(languages)

In this example, we insert "python" at the beginning of the languages list(Since 0 is the first index position).

['java', 'php', 'javascript', 'perl']
['python', 'java', 'php', 'javascript', 'perl']

Example 2

languages = ["java", "php", "javascript", "perl"]
print(languages)
languages.insert(2, "python")
print(languages)

In this example, we insert "python" to the index position "2", which means the third element of the languages list. As a result of this "Javascript" and "perl" will shifts one position to the right.

['java', 'php', 'javascript', 'perl']
['java', 'php', 'python', 'javascript', 'perl']

Summary - Python Append to List

  • In python 3, append() method, add items to the end of the list.
  • Python insert() function, insert elements at any position by the index of the new element.