Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

Difference Between append() and extend() Method in Python

append() and extend() methods are used to add more items or elements to an already existing list in Python Programming Language. Let’s understand the difference between append() and extend() method in Python.
 

append() method in Python

append() adds a single element at the end of the list. For example

Output:
['a', 'b', 'c', 'd']

In the above example, we added ‘d’ element at the end of the already existing myList. Remember that append() method adds the item or element at the end of the list. Let’s take another example

output:
['a', 'b', 'c', '[d,e]']

In this example ‘[d,e]’ is a single list element that is appended at the end of the list. append() method can add only single element to the list.

 
Now we look at extend() method in Python.
 

extend() method in Python

extend () method is used to add multiple items at the end of an already existing list. Let’s clear it by taking an extend() method example

output:
['a', 'b', 'c', 'd']

extend() method can do the same thing as append method do. In the above example we added ‘d’ element as we did in append() method example. But we can use extend() method to add any number of items in the list. Let’s add more than one item by using extend() method for list.

output:
['a', 'b', 'c', 'd', 'e']

In the above example, we added two items in the list by using extend method. We can add any number of elements into the list by using extend() method in Python.

 

Loading...
LearnAndLearn.com © 2018 - All rights reserved