Skip to content

Python list insert at end | Example code

  • by

Use the insert method to add a new element at the end of the list in python. This inbuilt function in Python inserts a given element at a given index in a list.

If given index >= length(list) is given, then it inserts at the end of the list.

list_name.insert(index, element)

Learn more about: Python list insert Function

Python list insert at the end example

Simple example code. If the given index is not found then it will throw an error.

Use len() function to index value for new element.

# List
list1 = [1, 2, 3, 4, 5, 6]

# Inserting value
list1.insert(len(list1), 7)

print(list1)

Output:

Python list insert at end

Add list to the end of list python

list1.extend(list2)

How to add an element in Python to the end of the list using list insert?

You have to pass the new ordinal position to insert using len in this case to the element at the end of the list:

a = [1, 2, 3, 4]
a.insert(len(a), 5)

print(a)

Output: [1, 2, 3, 4, 5]

Do comment if you have any doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading