In this article, we will discuss python list append and extend functions. We’ll also check the performance of the functions.
List append
The append function is used to add an item to the end of the list.
The syntax of append function
list.append(x)
Examples
Add a single item to list
languages = ["English","French","Hindi"]
languages.append("Spanish")
print(languages)
Output
['English', 'French', 'Hindi', 'Spanish']
Add multiple items to the list. We can loop and add items to the list. ( We can also use extend function)
languages = ["English","French","Spanish"]
ind_languages = ["Tamil","Hindi"]
for language in ind_languages:
languages.append(language)
print(languages)
Output
['English', 'French', 'Spanish', 'Tamil', 'Hindi']
Append list to the end of the list
languages = ["English","French","Spanish"]
ind_languages = ["Tamil","Hindi"]
languages.append(ind_languages)
print(languages)
Output
['English', 'French', 'Spanish', ['Tamil', 'Hindi']]
List extend
The list extend function is used to extend a list by appending all the items from iterable.
Syntax of list extend
list.extend(iterable)
Examples
To append a sublist of items to another list we can use the extend function.
languages = ["English","French","Spanish"]
ind_languages = ["Tamil","Hindi"]
languages.extend(ind_languages)
print(languages)
Output
['English', 'French', 'Spanish', 'Tamil', 'Hindi']
Which is method is faster?
To add another list either we can use these functions. Let’s compare the speed of these functions.
Let’s create a list of 100 numbers and add 1000 items to it.
import time
x = list(range(1, 101))
y = list(range(2000,3001 ))
start= time.time()
x.extend(y)
elapsed= time.time()- start
print( f"Elapsed time : {elapsed} sec")
Output
Elapsed time : 9.036064147949219e-05 sec
Lets loop and add items using append
import time
x = list(range(1, 101))
y = list(range(2000,3001 ))
start= time.time()
for z in y:
x.append(z)
elapsed= time.time()- start
print( f"Elapsed time : {elapsed} sec")
Output
Elapsed time : 0.00475311279296875 sec
From this, we can see that extend the function is much faster than append. If we want to add a list of items to another list we can use extend function.
Conclusion
In conclusion, list append and extend are useful functions. To add a single item we can use the append function and we can use the extend function to add sub-list items. You can read about list len function performance here.