We have arrived at the right place if we want to understand how to use the append() and extend() function and their differences in Python. In our Python projects, we will undoubtedly employ these robust list methods.
- Python Extend Vs Append
- How to add elements in the list using the extend vs append
- Which one is faster Extend or Append function
Python Extend Vs Append
The following are the distinctions between Python’s add() and extend() methods:
- A single element is added to the end of a list using the append() function.
- The extend() method adds many elements.
Here is a brief comparison chart that explains the differences.
append() function | extend() function |
Adds the input to the list as a single element. | Adds a number of items to a list. |
O(1) or constant time complexity. | The number of list elements, n, determines the time complexity, which is O(n). |
Length grows by one. | The length grows as more items are included. |
The above chart shows the difference between extend() and append(), in the next subsections we will learn about how the extend() and append() function works.
Read: Python program for binary search
Python Extend Vs Append List
Append method in Python
The append() method in Python adds one element to an already-existing list. Instead of returning the element to a new list, it will be appended to the end of the old list. adds its argument to a list’s end as a single element. The list becomes one item longer.
Since lists can include elements of several data types, we can add items of any data type.
The syntax is given below
list_name.append(item)
Where,
- list_name: It is the name of the list that we want to modify or where items need to be added.
- append(): It is the function that takes an argument as a single element within the parenthesis to add that element to the list_name.
- item: It is the element or item that is added to the list_name, it can be any data type or object like numbers, float, string and etc.
The dot plays a crucial role. It is known as “dot notation.” The impact of the function will be applied to the list that is positioned before the dot since the dot essentially says, “Call this method on this specific list”.
Let’s take an example and see how the method append()
add an element to the list by following the below steps:
Create a list that contains the number of deaths in the top four states of the USA in 2020 such as California = 59778
, Florida = 45800
, Texas = 42142
and New York = 32955
.
usa_death = [59778, 45800, 42142, 32955]
Suppose we want to add the number of deaths in the state Pennsylvania = 27955
to the end of the list, which is going to be the fifth state of the USA or we want to modify the list such that it contains the number of deaths in the top five states of the USA. For that use the below code.
usa_death.append(27955)
Check the modified list “usa_death” using the below code.
print(usa_death)
Look in the above output, how to list is modified and added new elements to the end of the list “usa_death”. Remember that original or the initial list is changed when we use the.append() function. Instead of making a copy of the list, the approach modifies the original list’s contents in memory.
In the above, we talked about the append() method can add any object to the end of the list which means we can add any numbers, float, string and even an entire list. Let’s see with an example.
In this example, we will add the list which contains the name of the states to the list “usa_death” by following the below steps:
usa_death_state = ["California", "Florida", "Texas", "New York", "Pennsylvania"]
Now add the entire list “usa_death_state” to the list “usa_death” using the below code.
usa_death.append(usa_death_state)
View the list “usa_death” using the below code.
print(usa_death)
The whole item is added to the end of the list using the append() method as in the above output. The complete sequence will be added as one item to the current list if the item is a sequence, such as a list, dictionary, or tuple.
Read: Remove a specific character from a string in Python
Extend method in Python
The extend() function extends the list and iteratively goes over its argument, adding each new element. As more components are included in its argument, the list grows longer.
The syntax is given below
list_name.extend(iterable)
Where,
- list_name: It is the name of the list that we want to modify or where items need to be added.
- extend(): It is the name of the function that takes an iterable as an argument.
- iterable: A string, list, dictionary, tuple, or set enclosed in parentheses that contains the items that will be inserted as distinct list elements.
Let me use a method you recently learned, the append() one, to demonstrate the significance of this one. According to what we have learned thus far, we would need to use append() numerous times, as shown below, in order to add a number of distinct items to a list using this method.
Create a new list using the below code.
data = [2,6,4,7] # We are going to modify this list
Append some of the numbers or elements using the below code.
# append the element in the list
data.append(9)
data.append(1.5)
data.append(6.3)
#check the modified list
print(data)
This would not be very effective, aren’t we sure? What if dozens or millions of values need to be added? For this straightforward activity, we cannot write thousands or millions of lines. That process would take ages.
However, there is an approach that is much more effective, readable, and condensed: extend().
Create a new list using the below code.
data = [2,6,4,7] # We are going to modify this list
Create the list of values that we want to add to the list “data” using the below code.
add_data = [9, 1.5, 6.3]
Pass the above-created list “add_data” to method extend() using the below code.
data.extend(add_data)
View the added number to the list “data” using the below code.
print(data)
Look in the above output, how the list containing numbers is added in one go using the method extend().
Read: How to remove the last character from a string in Python
Python Extend Vs Append Speed
Which one is faster? Below is a simple script that evaluates the performance of building huge lists with progressively larger lengths using the extend() and append() methods in order to provide an answer to this query.
Due to Python’s ability to append entries to a list in batches rather than calling the same method repeatedly, the extend() method ought should be quicker for bigger list sizes.
Firstly, build two functions list by append(n) and list by extend(n) that take an integer list size of n as an input argument and, using the append() and extend() functions, respectively, create lists of successively increasing integer entries.
import time
def list_for_append(ele_n):
'''creates a list and appends n additional elements to it'''
lst_ = []
for i in range(ele_n):
lst_.append(ele_n)
return lst_
def list_for_extend(ele_n):
'''creates a list and extends n additional elements to it'''
lst_ = []
lst_.extend(range(ele_n))
return lst_
Secondly, we use 100 distinct list size n values to compare the runtimes of the two functions.
# Compare the two functions' running times
lst_sizes = [i * 10000 for i in range(100)]
append_rtimes = []
extend_rtimes = []
for size in lst_sizes:
# Obtain time stamps.
time0 = time.time()
list_for_append(size)
time1 = time.time()
list_for_extend(size)
time2 = time.time()
# Compute runtimes
append_rtimes.append((size, time1 - time0))
extend_rtimes.append((size, time2 - time1))
Thirdly, Graph the runtimes of both functions using the below code.
import matplotlib.pyplot as plt
import numpy as np
append_rtimes = np.array(append_rtimes)
extend_rtimes = np.array(extend_rtimes)
print(append_rtimes)
print(extend_rtimes)
plt.plot(append_rtimes[:,0], append_rtimes[:,1], label='append()')
plt.plot(extend_rtimes[:,0], extend_rtimes[:,1], label='extend()')
plt.xlabel('List size')
plt.ylabel('Runtime in (seconds)')
plt.legend()
plt.savefig('append_vs_extend.jpg')
plt.show()
This graphic compares the runtimes of the two methods, add() and extend (). We can now see the list size on the x-axis, which ranges from 0 to 1,000,000 entries. We can see the runtime, measured in seconds, required to carry out each function on the y-axis.
The resulting plot demonstrates that both approaches are quite quick for a small number of tens of thousands of items. They move so quickly in fact that the time() method of the time module is unable to record the passing of time.
However, the extend() approach begins to prevail once the size of the lists is increased to hundreds of thousands of elements.
You may also like to read the following Python tutorials.
- How to Python Append List to Another List
- How to find perfect number in Python
- How to reverse a number in Python
- Sum Elements in List in Python using For Loop
At the end of this Python tutorial, we understood the key differences between append and extend methods in Python. Also, we discussed the following topics.
- Python Extend Vs Append
- How to add elements in the list using the extend vs append
- Which one is faster Extend or Append function
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.