Python Tutorials

Difference between append and extend in python

append() method

append(): The provided argument to this method is added to the list as a single element. The length of the list always increases by 1.

my_list = [1,2,3]
my_list.append('test')
print(my_list)

Output:

>>>[1,2,3,'test']


Let's append a different list to existing list:

my_list = [1,2,3,'test']
my_list.append([4,5,6])
print(my_list)

Output:

>>>[1,2,3,'test',[4,5,6]]

Note : The length of my_list is still increased by 1 as we appended the whole list as a single element to it


extend method()

extend(): When we provide argument to extend(), it iterates over the argument and add each iterated element to the list separately. The length of the list increases by length of the argument.

my_list = [1,2,3]
my_list.extend('test')
print(my_list)

Output:

>>>[1,2,3,'t','e','s','t']

Note: The length is increased by 4 


Let's extend a list:

my_list = [1,2,3,'t','e','s','t']
my_list.extend([4,5,6])
print(my_list)

Output:

>>>[1,2,3,'t','e','s','t',4,5,6]

Note: The length is increased by 3