Practice Adding and Removing Elements
00:08 So I’m just going to be working with colors instead of the numbers list. I’ve added color emoji dots, but then also the starting letter of the color so that everyone can understand what these colors are if in case they look the same to you, they’re meant to be different color dots.
But you can also refer to the letters on the side. So the first one is a red color dot, and we also have an
r next to it. And then there’s a green color dot, and we have a
g next to it, and a blue color dot with a
b next to it.
00:58 And then I need to first give the index position where I want to insert it, and then the object I want to insert. So I want to insert orange at the index one, which is going to be after red and before green.
So I’m creating the string that I want to add and then pick out the violet color dot and add a
v for violet. And after executing this, you can see that the colors list now contains red, orange, green, blue, and violet.
02:21 And then you can also extend a list. Let’s start with a different list. For that, I’m going to use a list that contains just the warm tones. So we have red, orange, and yellow in here in that list, and I want to extend it with green, blue, and violet.
Any sort of collection works, so here I’m passing a string, which looks like it’s a single element, but it consists of two characters and it’s iterable. So you can see that
warm_tones changed in a way that I didn’t intend.
Let’s look at that.
warm_tones.extend() and then pass in an iterable. I’m going to do a tuple. You could also do a list instead. So here I’m adding a tuple that has three values in it, green, blue, and violet.
It’s not great naming anymore because these are not all warm tones.
warm_tones shouldn’t contain green, blue, and violet actually. So let’s get rid of them. I’m going to say
warm_tones.pop() and remove.
04:34 Let’s take off blue at first. That seems like the least warm for me. So I’m going to figure out at which index position is this? Red is at zero, orange is at one, yellow is at two, green is at three, and blue is at four.
Let’s also get rid of the other two. So if you don’t define any sort of index position, then Python just pops from the end. So if I run
warm_tones.pop(), then it’ll give me back violet, and it has removed it from
05:41 This is just a slightly different example than the numbers list that you’ve seen in the slides. I hope it’s maybe visually a bit more interesting for you to see like how lists are mutable and how you can use these handy list methods to insert elements, append elements at the end, pop elements from somewhere in the list or from the end, and also extend the list with an iterable so you can add more elements at the same time.
Become a Member to join the conversation.