Python

append() method in list

Click for All Topics

append() method in list - Python

  • This method is used to add an item to the list at the end.
  • It modifies the original list.
  • This method doesn’t return any value.
  • This method takes exactly one argument.
  • You can pass any data type element(e.g. int, float, tuple, etc.) as an argument in the append() method.
  • Generally, this method takes O(1) constant time to add an element to the list.
  • Sometimes it may take O(n) time, it happens when the allocated memory of the list is insufficient to add an element to the list ,in this scenario python simply doubles the allocated memory of the list and then adds an element to the list.

Syntax –

list.append(item)

Parameters –

  • item → any data type element e.g. int, float, string, list, tuple, etc.
  • return value → None(It doesn’t returns anything)
Example  1-
				
					my_list=[10,20,30,40]
print("Original list: ",my_list)
my_list.append(50)
print("My list after appending 50: ",my_list)

# Output -
# Original list:  [10, 20, 30, 40]
# My list after appending 50:  [10, 20, 30, 40, 50]
				
			
  • In the above example, first we create a list with elements 10 to 40 and store it in the my_list variable.
  • After creating my_list, print the original list on the output screen.
  • Add one more element(40) to the list using the .append() method.
  • Finally, print the modified list on the output screen.

Adding a list to the list – you can also add a list to the list using the .append() method.

Example 2-
				
					my_list=['edSlash', 'official']
print("Original list : ",my_list)
my_list.append(['Data Science','Gwalior'])
print("My list after appending another list :",my_list)

# Output -
# Original list :  ['edSlash', 'official']
# My list after appending another list : ['edSlash', 'official', ['Data Science','Gwalior']]
				
			

Example 3 – add all even elements to the list

				
					l=[]
print("Original list :",l)
for i in range(20):
	if i%2==0:
		l.append(i)
print('List after appending all even elements in a range of 20')
print(l)

# Output -
# Original list : []
# List after appending all even elements in a range of 20
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
				
			

Example 4 – append a dictionary to the list

				
					lst=['a','b','c','d']
print("Original list :",lst)
dct={'a':1,'b':2,'c':3}
lst.append(dct)
print("Modified original list :",lst)

# Output - 
# Original list : ['a', 'b', 'c', 'd']
# Modified original list : ['a', 'b', 'c', 'd', {'a': 1, 'b': 2, 'c': 3}]