Add and Remove List Elements
But lists actually have useful methods that allow you to add and remove elements. For example,
.insert(), where you first pass the index where you want to insert the element and then the element that you want to insert;
.append(), in which you just pass an element as an argument and it adds it to the end of the list;
.extend(), where you can pass as an argument an iterable, so some sort of a collection, and then it adds it to the end of the list; and
.pop(), where you can optionally pass an index, and then it’ll remove the element at that specified index.
So I want to insert an element at the index one, which is currently where the value
3 sits. And there I want to insert
"two", and I’m just using a string here just to make it a little more obvious what happens, because if you have two integers here as arguments, then it might get a little confusing what is the index and what is the value.
You can also use
.append() to add an element to the end of the list, which is a very common operation, for example, if you’re looping over some data structure and you want to append specific elements that you found in there to a list.
In this example, you have again the
numbers list consisting of two elements,
2, and then you say
numbers.append(), and then pass the integer
3 in this case as the argument, and then the
numbers list is going to consist of three elements,
Then you can use
.extend() to add a collection at the end of the list. So that’s not just a single element, but more than one element. Same example,
numbers list as before, consisting of two elements,
2, and then you’re calling
.extend() on the
numbers list and passing it another list.
So it’s important that this is an iterable that you’re passing to
.extend(). This can’t be just a single value. It can be a single value, but it has to be a collection that then contains just one value.
4 is the extended version. And you can see that it’s still the
numbers list. So Python mutated this list, added two values at the end, and you can do this with any sort of collection.
Become a Member to join the conversation.