append() and extend() methods are used with the list in the Python programming.
append()
append() method adds the argument at the end of the existing list. It does not return a new list rather it modifies the original list.
Example:
original_list = [1,2,3,4]
print(original_list)
original_list.append(5)
print("Updated List: ",original_list)
OUTPUT:
[1, 2, 3, 4]
Updated List: [1, 2, 3, 4, 5]
If you pass another list as an argument to the append() method, it will add that entire list to the last index of the original list making it a 2D (two dimensional) list.
Example:
original_list = [1,2,3,4]
print(original_list)
other_list = [5,6,7]
original_list.append(other_list)
print("Updated List: ",original_list)
OUTPUT:
[1, 2, 3, 4]
Updated List: [1, 2, 3, 4, [5, 6, 7]]
extend()
extend() method combines two lists into a single one. In fact, it adds the components of the list given as the argument iteratively to the end of the original list.
Example:
original_list = [1,2,3,4]
print(original_list)
other_list = [5,6,7]
original_list.extend(other_list)
print("Updated List: ",original_list)
OUTPUT:
[1, 2, 3, 4]
Updated List: [1, 2, 3, 4, 5, 6, 7]
As we know that the extend() method reads the argument iteratively. And a string is also iterable, So, when we provide a string as the argument to the extend() method, it will append each character separately into the original list.
Example:
original_list = [1,2,3,4]
print(original_list)
original_list.extend('codesposts')
print("Updated List: ",original_list)
OUTPUT:
[1, 2, 3, 4]
Updated List: [1, 2, 3, 4, 'c', 'o', 'd', 'e', 's', 'p', 'o', 's', 't', 's']