Python List Append and Extend Difference

0
367
Python List Append and Extend

The difference between Python list append and extend tends is a source of confusion for both data scientist and programmers.

So in this post we will discuss how they are different

So first  let’s create a simple list:

mylist = ['a','b','c']

 

APPEND

The append method is used to add a single item into a list.

IF we want to add the string 'd' into mylist we use append.

Input:

mylist.append('d') 
mylist

Output:

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

How about if we want to add both strings 'e' and 'f' this time?

Can we use mylist.append(‘e’,’f’)?.

No. This will return an error.  As the append can only take in only one argument.

How about if we put 'e' and 'f' in a list.  What will happen?

Input:

mylist.append(['e' ,'f']) 
mylist

Output:

 ['a' , 'b', 'c', 'd', ['e' , 'f']]

The output returned an embedded list.

So what do we do to add multiple items in a list? We use the method extend.

EXTEND 

Extend is a python list method which allows multiple items to be added to a list.

The requirement is that the items should be an element of an iterable (e.g. list, tuple)

Input:

mylist.extend(['e' , 'f'])
mylist

Output:

 ['a' , 'b', 'c', 'd', 'e', 'f']

 

Using append to add elements to a list one by one is really exhausting and unnecessary.

CONCLUSION

Python list append and extend are somehow similar that both add elements in the end.

The main difference is that append can only take one item to be added while extend adds multiple items from an iterable (e.g. list).

Use append when adding a single item.

Use extend when adding multiple items.

To learn more about other Python list method / operations click here: 

http://www.thedatalife.com/python-list-functions-methods-operations/

If you want to learn about slicing or indexing of list:

http://www.thedatalife.com/python-list-slicing-indexing/

For official documentation about Python list and extend methods visit the following:

https://docs.python.org/3.3/tutorial/datastructures.html

LEAVE A REPLY

Please enter your comment!
Please enter your name here