Python tutorial on Append vs Extend in Python Lists
Adding Elements to a List
Lists are one of the most useful data structures available in Python, or really any programming language, since they’re used in so many different algorithms and solutions.
Once we have created a list, often times we may need to add new elements to it, whether it be at the end, beginning, or somewhere in between. Python offers us three different methods to do so. In this article I’ll be showing the differences between the
insert list methods.
This method adds an element at the end of an existing list. The syntax to use it is:
Here the variable
a is our list, and
x is the element to add. This expression is equivalent to
a[len(a):] = [x].
For example, here is how to use it to place the element “y” at the end of our list,
a = [1, 'x', 2] a.append('y') print(a)
Running this code will result in the following output:
$ python append.py [1, 'x', 2, 'y']
This method inserts an item at a specified position within the given list. The syntax is:
Here the argument
i is the index of the element before which to insert the element
a.insert(len(a), x) is the same thing as
a.append(x). Although, the power of this method comes in using it to place items somewhere within the list and not at the end. If you only needed to add an element to the end of the list then
append works just fine for that, and is faster (which matters for large lists).
a = [1, 'x', 'y'] a.insert(2, 2) print(a)
This code will result in the following output:
$ python insert.py [1, 'x', 2, 'y']
As you can see, the element given is placed anywhere in the list that we specify. This works well when you have a list in which its items are ordered, so you can’t just add your element to the end, like you would do with
This method adds elements (notice its plural!) to a list by adding on all the elements of the iterable you pass to it. The resulting list is one containing all of the elements of both lists.
The syntax for using this method is:
In this case
a is our list and
x is an iterable object, such as another list. This method is equivalent to
a[len(a):] = x.
a = [1, 'x', 'y'] b = [1, 2] a.extend(b) print(a)
Running this code results in the following output:
$ python extend.py [1, 'x', 'y', 1, 2]
Notice how the two lists were combined together, one after the other.
In Python, you can also achieve the same results by doing a simple addition. So
a + b, in this case, would result in the same exact array as our script above. This is thanks to the
__add__() method being implemented in the lists, but that’s out of the scope of this article.
Comparing Each Method
In order to see the different results obtained through these methods, let’s do a direct comparison by running the following code:
a1 = [1, 'x', 'y'] a2 = [1, 'x', 'y'] a3 = [1, 'x', 'y'] b = [2, 3] a1.append(b) a2.insert(3, b) a3.extend(b) print(a1) print(a2) print(a3)
In this program, we have defined three lists with exactly the same elements. We have also defined a second list, which we append, insert and extend to each of the three similar lists previously defined. The result is as follows:
$ python all.py [1, 'x', 'y', [2, 3]] [1, 'x', 'y', [2, 3]] [1, 'x', 'y', 2, 3]
As we can see, both
insert add the list
b to the initial list, but as a single element, which is a list. In other words, it doesn’t append each element of
b individually, but instead it appends the entire object itself.
extend method, on the other hand, actually adds the individual elements of list
b, as separate and unique elements of the resulting list.
This is all in agreement with what we previously saw, that is,
insert add only a single element. Whereas,
extend, expands on the initial list by adding the elements of the second list at its end.
Another difference to consider is the measure of efficiency. Given how each operation works, we can pretty easily figure out the time complexity for each method. Or you can just cheat and check out the Time Complexity page on python.org’s wiki page.
The time complexities are as follow:
Here “n” is the number of elements currently in the list, and “k” is the number of elements in the parameter object.
These points show that these three methods are complementary. We must choose which one to use, according to our needs:
- If we want to add an element at the end of a list, we should use
append. It is faster and direct.
- If we want to add an element somewhere within a list, we should use
insert. It is the only option for this.
- If we want to combine the elements of another iterable to our list, then we should use
Python presents several choices to add elements into a list, all of which complement each other and have their own use-cases. In this article we presented three of those choices, how to use each, and when to use each. The choice of method you choose should be based on your needs.
Python Example for Beginners
Two Machine Learning Fields
There are two sides to machine learning:
- Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
- Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.
Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes
Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!
Latest end-to-end Learn by Coding Recipes in Project-Based Learning:
Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.