Add an element at the end of a List in Python

This tutorial will discuss about unique ways to add an element at the end of a list in Python.

Table of Contents

Using list.append() function to add element at the end of list

In Python, the list class provides a function append(). It accepts a single argument, and addes that element at the end of list. This element can be a number, string, or an object of any other type. So, in this example, we will call the append() function to add a given number to a list in Python.

Let’s see the complete example,

listOfNumbers = [21, 22, 23, 24, 25, 26]

# element to be added in the end of list
num = 99

# Append element at the end of list
listOfNumbers.append(num)

print(listOfNumbers)

Output

Advertisements
[21, 22, 23, 24, 25, 26, 99]

It added an item at the end of list.

Using list.insert() function to add the element at end of list

Python List provides an another function insert(index, element). It is used to insert a given element at the specified index in the list. It accepts two arguments,

  • Index position, at which we want to insert the element
  • Element to be inserted

It then inserts the given element at the specified position in the list.

As the index starts from 0 in the list, so to add an element at the end of list, pass size of list as the first argument, and the element to be added as the second argument in the insert() function. It will add the given element at the end of list.

Let’s see the complete example,

listOfNumbers = [21, 22, 23, 24, 25, 26]

# element to be added in the end of list
num = 99

# Append element at the end of list
listOfNumbers = [*listOfNumbers, num]

print(listOfNumbers)

Output

[21, 22, 23, 24, 25, 26, 99]

It added an item at the end of list.

Using astrik to unpack list to add the element at end of list

We will create a new list. First we will apply astrik operator on original list to unpack all elements of this list as individual items. Then add these unpacked items to a new list. Then add the new element to this list. In the end, assign this new list to the same original variable. This way a new element is added at the end of list in Python.

Let’s see the complete example,

listOfNumbers = [21, 22, 23, 24, 25, 26]

# element to be added in the end of list
num = 99

# Append element at the end of list
listOfNumbers.insert(len(listOfNumbers), num)

print(listOfNumbers)

Output

[21, 22, 23, 24, 25, 26, 99]

It added an item at the end of list.

Summary

We learned about three different ways to add an element at the end of a list in Python.

Advertisements

Thanks for reading.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top