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']
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.
['a' , 'b', 'c', 'd']
How about if we want to add both strings
'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
'f' in a list. What will happen?
mylist.append(['e' ,'f']) mylist
['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 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)
mylist.extend(['e' , 'f']) mylist
['a' , 'b', 'c', 'd', 'e', 'f']
Using append to add elements to a list one by one is really exhausting and unnecessary.
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.
If you want to learn about slicing or indexing of list:
For official documentation about Python list and extend methods visit the following: