Use append, insert or extend the method to add elements into a List in Python. Every method to list with different way:-
- append(): add the object to the end of the list.
- insert(): add the object before the given index.
- extend(): It extends the list by appending elements from the iterable.
- List Concatenation: Use + operator to concatenate multiple lists and create a new list.
Python add to list Example code
Simple Python programs:-
To add an item to the end of the list.
list1 = ["Apple", "Banana", "Guva"] list1.append("Orange") print(list1)
Insert a list item at a specified index.
list1 = ["Apple", "Banana", "Guva"] list1.insert(1,"Orange") print(list1)
To append elements from another list to the current list. The elements will be added to the end of the list.
list1 = ["Apple", "Banana", "Guva"] list2 = ["Mango", "Pineapple"] list1.extend(list2) print(list1)
concatenate multiple lists using the overloaded + operator.
evens = [2, 4, 6] odds = [1, 3, 5] nums = odds + evens print(nums)
Do comment if you have any doubts and suggestions on this Python list tutorial.
Note: IDE: PyCharm 2021.3.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.