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.
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)
Add list to end of list python
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.