Python provides methods like append
and extend
to add elements to the existing list.
In this shot, we will go through the differences between the methods append()
and extend()
.
append()
Python’s append()
method is used to add elements to the existing list.
It will append the object to the end of the list.
list.append(element)
The append()
method will accept an element as a parameter, and it will add that to the list.
In the following code snippet:
fruits
with ["apple","banana","grapes"]
.orange
to the end of the list with the append()
method.fruits = ["apple","banana","grapes"]print("list of fruits before append -> " + str(fruits))fruits.append("orange")print("list of fruits after append -> " + str(fruits))
If we try to append a list to an existing list, the whole list will be treated as one element and it appends as one.
In the following code snippet:
["peach","mango","watermelon"]
to fruits
list will be treated as one element, and will be added at the end as ['apple', 'banana', 'grapes', ['peach', 'mango', 'watermelon']]
.#initialization of listfruits = ["apple","banana","grapes"]#print before appendingprint("list of fruits before append -> " + str(fruits))#appending entire listfruits.append(["peach","mango","watermelon"])#print after appendingprint("list of fruits after append -> " + str(fruits))
extend()
The extend()
method acts the same as the append()
method if we add a single element, but it behaves differently if we add a list.
In the following code snippet:
fruits
list with ["peach","mango","watermelon"]
will result in ['apple', 'banana', 'grapes', 'peach', 'mango', 'watermelon']
, as the extend()
method adds elements provided to it individually to the fruits
list.#initialization of listfruits = ["apple","banana","grapes"]#print before extendprint("list of fruits before extend -> " + str(fruits))#appending entire listfruits.extend(["peach","mango","watermelon"])#print after extendprint("list of fruits after extend -> " + str(fruits))