Add elements to the list in python
Table of Content:
Add Item to a List
append() method is used to add an Item to a List.
list=[1,2] print('list before append', list) list.append(3) print('list after append', list)
Output
list before append [1, 2] list after append [1, 2, 3]
Add Item Using extend() Function
NOTE :- extend() method can be used to add multiple item at a time in list.
list=[1,2] print('list before extend', list) list.extend([3,4]) print('list after extend', list)
Output
list before extend [1, 2] list after extend [1, 2, 3, 4]
append() list Items using for loop
Python provides append() function which is used to add an element to the list. However, the append() function can only add value to the end of the list. Consider the following example in which, we are taking the elements of the list from the user and printing the list on the console.
#Declaring the empty list l =[] #Number of elements will be entered by the user n = int(input("Enter the number of elements in the list:")) # for loop to take the input for i in range(0,n): # The input is taken from the user and added to the list as the item l.append(input("Enter the item:")) print("printing the list items..") # traversal loop to print the list items for i in l: print(i, end = " ")
Output
Enter the number of elements in the list:5 Enter the item:25 Enter the item:46 Enter the item:12 Enter the item:75 Enter the item:42 printing the list items 25 46 12 75 42
insert() function
The insert() function adds the element passed to the index value and increase the size of the list too.
my_list = [1, 2, 3] print(my_list) my_list.insert(1, ‘Sunny') #add element at 1 print(my_list)
Output
[1, 2, 3] [1, ‘Sunny’, 2, 3, 4, 5]
Add Two Lists
list = [1,2] list2 = [3,4] list3 = list + list2 print(list3)
Output
[1, 2, 3, 4]
Example: Write the program to remove the duplicate element of the list.
list1 = [1,2,2,3,55,98,65,65,13,29] # Declare an empty list that will store unique values list2 = [] for i in list1: if i not in list2: list2.append(i) print(list2)
Output
[1, 2, 3, 55, 98, 65, 13, 29]