In python append, extend, and insert are list functions used to add elements to a list. All of the three functions are quite useful when working with lists and have their own specific use cases. In this article, we’ll dive into the application of these functions, their syntax and how are they different from each other?
Before we proceed, here’s a quick refresher on python lists – Lists are used to store an ordered collection of items. These items can be any type of object from numbers to strings or even another list. This makes lists are one of the most versatile data structures in python to store a collection of objects. For more, check out our guide on lists and other data structures in python.
How to add elements to a list?
Lists are quite useful when it comes to storing sequences or collections and are frequently used in python. It may happen that you want to add elements to an existing list. To do so, the list functions append()
, extend()
, and insert()
are commonly used.
The append() function
The append()
list function in python is used to add an item to the end of the list. The following is the syntax:
sample_list.append(x)
Here, sample_list is the list to which you want to append the item and x is the item to be appended. The functionality of the append function is equivalent tosample_list[len(sample_list):] = [x]
Note that the append()
function does not return a list, rather it modifies the list in-place, meaning the list on which the function is applied gets updated.
Example:
# add element to list using append function
ls1 = [1,2,3,4]
ls2 = [1,2,3,4]
x = 5
# print the original lists
print("Before Append")
print("ls1:", ls1)
print("ls2:", ls2)
# append x to ls1 and ls2
# use append function for ls1
ls1.append(x)
# use slicing and assignment for ls2
ls2[len(ls2):] = [x]
# print updated lists
print("After Append")
print("ls1:", ls1)
print("ls2:", ls2)
Output:
Introductory ⭐
- Harvard University Data Science: Learn R Basics for Data Science
- Standford University Data Science: Introduction to Machine Learning
- UC Davis Data Science: Learn SQL Basics for Data Science
- IBM Data Science: Professional Certificate in Data Science
- IBM Data Analysis: Professional Certificate in Data Analytics
- Google Data Analysis: Professional Certificate in Data Analytics
- IBM Data Science: Professional Certificate in Python Data Science
- IBM Data Engineering Fundamentals: Python Basics for Data Science
Intermediate ⭐⭐⭐
- Harvard University Learning Python for Data Science: Introduction to Data Science with Python
- Harvard University Computer Science Courses: Using Python for Research
- IBM Python Data Science: Visualizing Data with Python
- DeepLearning.AI Data Science and Machine Learning: Deep Learning Specialization
Advanced ⭐⭐⭐⭐⭐
- UC San Diego Data Science: Python for Data Science
- UC San Diego Data Science: Probability and Statistics in Data Science using Python
- Google Data Analysis: Professional Certificate in Advanced Data Analytics
- MIT Statistics and Data Science: Machine Learning with Python - from Linear Models to Deep Learning
- MIT Statistics and Data Science: MicroMasters® Program in Statistics and Data Science
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
Before Append
ls1: [1, 2, 3, 4]
ls2: [1, 2, 3, 4]
After Append
ls1: [1, 2, 3, 4, 5]
ls2: [1, 2, 3, 4, 5]
In the above example, we see how the append function is applied. We append the element x
to the list ls1
using the append()
function and compare the results from its equivalent operation using slicing and assignment. Append is a built-in list function and is actually a cleaner(more readable) way to add items to the end of the list.
The extend() function
The extend
list function in python is used to append each element of an iterable (example, list, tuple, string, etc) to the list. That is, instead of adding the iterable itself as an object (what append does) it appends each element of the iterable to the list. The following is the syntax:
sample_list.extend(sample_iterable)
Here, sample_list is the list you want to extend and sample_iterable is the iterable whose elements you want to append to the list. The functionality of the extend function is equivalent to sample_list[len(sample_list):] = sample_iterable
Note that, like the append()
function, the extend()
function also does not return a list, rather it modifies the list in-place, meaning the list on which the function is applied gets updated.
Example:
# add item to list using extend
ls1 = [1,2,3]
ls2 = [1,2,3]
x = [4,5]
# print the original lists
print("Before Extend")
print("ls1:", ls1)
print("ls2:", ls2)
# add x to ls1 using extend
ls1.extend(x)
# add x to ls2 using slicing and assignment equivalent
ls2[len(ls2):] = x
# print updated lists
print("After Extend")
print("ls1:", ls1)
print("ls2:", ls2)
Output:
Before Extend
ls1: [1, 2, 3]
ls2: [1, 2, 3]
After Extend
ls1: [1, 2, 3, 4, 5]
ls2: [1, 2, 3, 4, 5]
In the above example, we see how the extend function is applied, we extend the list ls1
with elements of the iterable x
using the extend()
function and compare the results from its equivalent operation using slicing and assignment. Like the append function, the extend function is a cleaner and more readable way to add the individual elements of an iterable to a list.
Difference between append and extend
Both append and extend are used to add elements to a list. But there’s an important difference between the two – The append function simply adds the object at the end of the list. If the object is an iterable, it does not add each element separately like extend does. The following example explains this difference:
# append vs extend
ls1 = [1,2,3]
ls2 = [1,2,3]
x = [4,5]
# print the original lists
print("Before")
print("ls1:", ls1)
print("ls2:", ls2)
# append x to ls1
ls1.append(x)
# extend x to ls1
ls2.extend(x)
# print updated lists
print("After")
print("ls1:", ls1)
print("ls2:", ls2)
Output:
Before
ls1: [1, 2, 3]
ls2: [1, 2, 3]
After
ls1: [1, 2, 3, [4, 5]]
ls2: [1, 2, 3, 4, 5]
In the above example, we apply the append function on ls1
and the extend function on ls2
. The append function simply appended [4,5]
as an object to the list ls1, while the extend function added each element of [4, 5]
to the list ls2.
The insert() function
Since lists are ordered sequences, it may happen that we require to add an element at a specific index. The insert()
function is used to insert an element at a specific index inside the list. The following is the syntax:
sample_list.insert(i, x)
Here, sample_list is the list you want to insert the element. The first argument, i, is the index at which you want to insert the element and the second argument, x, is the element to be inserted.
Note, like append and extend, insert also does not return a list. It modifies the list in-place.
Example:
# insert
ls = ['red', 'blue', 'green']
# print the original list
print("Before")
print("ls:", ls)
# insert 'yellow' at the 1st index
ls.insert(1, 'yellow')
# print the updated list
print("After")
print("ls:", ls)
Output:
Before
ls: ['red', 'blue', 'green']
After
ls: ['red', 'yellow', 'blue', 'green']
In the above example, we use the insert function to insert the string yellow
at the index 1
.
Time Complexity Comparison
The following table shows the time complexities of the three functions:
Function | Time Complexity |
---|---|
append() | O(1) |
extend() | O(k) |
insert() | O(n) |
We see that of the three methods, append is the quickest. The extend function has a linear time complexity with respect to the size of the parameter (that is, the iterable) while the insert function has a linear time complexity with respect to the size of the list on which the function is applied.
For more on time complexity of different functions in python refer to the python wiki.
Tutorials on python lists:
- Python – Check if an element is in a list
- Python – Iterate over multiple lists in parallel using zip()
- Python – Flatten a list of lists to a single list
- Pandas DataFrame to a List in Python
- Python – Convert List to a String
- Convert Numpy array to a List – With Examples
- Python List Comprehension – With Examples
- Python List Index – With Examples
- Python List Count Item Frequency
- Python List Length
- Python Sort a list – With Examples
- Python Reverse a List – With Examples
- Python Remove Duplicates from a List
- Python list append, extend and insert functions.
- Python list remove, pop and clear functions.
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.