Python list insert at end | Example code

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 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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

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