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:-
append()
To add an item to the end of the list.
list1 = ["Apple", "Banana", "Guva"]
list1.append("Orange")
print(list1)
Output:
insert()
Insert a list item at a specified index.
list1 = ["Apple", "Banana", "Guva"]
list1.insert(1,"Orange")
print(list1)
Output:
extend()
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)
Output:
List Concatenation
concatenate multiple lists using the overloaded + operator.
evens = [2, 4, 6]
odds = [1, 3, 5]
nums = odds + evens
print(nums)
Output:
Do comment if you have any doubts and suggestions on this Python list tutorial.
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.