Difference between Python methods append and extend?

Explanation

The difference between python methods append and extend are:

Append is used to insert the element at the end of the list. So it will modify the list by adding the elements in the last of the list. So the size of the list gets incremented as we use the append method.  So we have the syntax of the method as:

Syntax: list_name.append(item)

An example is as follows:

x = [1, 2, 3]
x.append([4, 5])
print(x)

So the output will be : [1, 2, 3, [4, 5]]

Whereas, Extend method is used to add the element at the end of the list. But it will add to the current list. So it will Extend the list by appending elements from the iterable.  And the syntax of the extend is :

Syntax: list.extend(iterable)

An example will be:

x = [1, 2, 3]
x.extend([4, 5])
print(x)

So we have output as : [1, 2, 3, 4, 5]

 

Also read, What does the explicit keyword mean?

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *