What is the difference between Python's list append and extend?
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.
Syntax
list.append(element)
Parameters
The append() method will accept an element as a parameter, and it will add that to the list.
In the following code snippet:
- Line 1: Initializes a list
fruitswith["apple","banana","grapes"]. - Line 2: Prints the list before using the append() method.
- Line 3: Adds an element
orangeto the end of the list with theappend()method. - Line 4: Prints the list after appending a new element.
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:
- Line 8: Appending the entire list
["peach","mango","watermelon"]tofruitslist 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.
- It will expand the original list, and add elements from the list.
In the following code snippet:
- Line 8: Extending the
fruitslist with["peach","mango","watermelon"]will result in['apple', 'banana', 'grapes', 'peach', 'mango', 'watermelon'], as theextend()method adds elements provided to it individually to thefruitslist.
#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))