Python’s list: What is the difference Between methods Append and Extend?

Here in this tutorial, We will discuss What is the difference between Python’s list methods append and extend? As both are used for adding elements in existing mutable lists in Python

Ways To Add Elements In An Existing List

append and extend in PythonAt times we need to add some elements to an existing list whereas at some times we need to add one element and at times a number of elements to add So for the different situations we have different methods so let’s discuss the ways.

Adding the new elements to the list leads to an increase in the size of the list that also we will discuss.

 

 

Append

It is one of the different ways to add a new element to a list. It is a way to add a single element to at the end of the existing list. We can only add one single element so it is used when we have to add one element at a time and that too at the end.

We can add multiple elements with append also but we need to write it every time when we need to add.

It has the advantage that we do not need to increase the size of the list it automatically increases the size depending on the elements added to the end of the list.

Let’s see using an example:-

>>> my_list
['foo', 'bar']
>>> my_list.append('baz')
>>> my_list
['foo', 'bar', 'baz']

Here we can see how an element as baz is added at the end of the existing list. As we can clearly see that we do not need to do anything for adding the storage, It itself accommodates according to the data we entered.

We can also add another list also at the end of one list, In this case, we simply need to give them a new list as a parameter of append.

Extends

Again it is also a way to add new elements in an existing list where we can add any number of new elements only by giving the size of how much we need to add and we can add the elements that we need.

Let’s see using an example:-

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

As we can see how we can provide the location where we want to add the new element and the element that we want to add.

 

Learn More About Extend and Appends: https://stackoverflow.com/questions/252703/what-is-the-difference-between-pythons-list-methods-append-and-extend

and learn here: How can I Randomly Select an Item from a List | Python List Problems with Answers

 

Leave a Comment

%d bloggers like this: