The append() and extend() functions are used with the python list to increase its number of elements. But the two have different behaviors as shown below.
append()
Syntax: list_name.append(‘value’) It takes only one argument.
This function appends the incoming element to the end of the list as a single new element. Even if the incoming element is itself a list, it will increase the count of the original list by only one.
Example
list = ['Mon', 'Tue', 'Wed' ] print("Existing list\n",list) # Append an element list.append('Thu') print("Appended one element: ",list) # Append a list list.append(['Fri','Sat']) print("Appended a list: ",list)
Output
Running the above code gives us the following result −
Existing list ['Mon', 'Tue', 'Wed'] Appended one element: ['Mon', 'Tue', 'Wed', 'Thu'] Appended a list: ['Mon', 'Tue', 'Wed', 'Thu', ['Fri', 'Sat']]
extend()
Extend adds each element to the list as an individual element. The new length of the list is incremented by the number of elements added.
Syntax: list_name.extend(‘value’) It takes only one argument.
Example
list = ['Mon', 'Tue', 'Wed' ] print("Existing list\n",list) # Extend an element list.extend("Thu") print("Extended one element: ",list) # Extend a list list.extend(['Fri','Sat']) print("Extended a list: ",list)
Output
Running the above code gives us the following result −
['Mon', 'Tue', 'Wed'] Extended one element: ['Mon', 'Tue', 'Wed', 'T', 'h', 'u'] Extended a list: ['Mon', 'Tue', 'Wed', 'T', 'h', 'u', 'Fri', 'Sat']