Changing List Objects
- 02:54
How to modify lists in Python, including how to update an existing item, add a new item using the append function, and remove an item with the remove function.
Downloads
No associated resources to download.
Transcript
After you make a list, there are going to be times that you want to go in and change an object within that list. Right here we have a list that represents a portfolio of tech stocks. So Apple, Amazon, Microsoft, Google, and then one object that we still need to update. So if I print that list, It looks like that. If I want to go in and change that TBD to let's say the ticker for Cisco, the way that I do that is I write the name of the list and then the index that matches the object in the list that I want to change. And then I just use the equals symbol to set a new value. So I'm gonna write the name and then in square brackets I'm going to put the index of the object. So remember lists our zero index. So 0, 1, 2, 3 is gonna gimme that fourth object. And then I use the equal sign to tell Python that I'm going to define a new value and I'm gonna change TBD to the string, CSCO, the ticker for Cisco. So now when I print that, You can see that that value has been updated in our list.
And if I want to add a new value to my list, that's very easy to do. I just use the append function. So I'm gonna write the name of my list tech portfolio, and then I'm gonna write the append function, do append open parentheses. And I'm going to add the object that I want to add to the end of the list. So let's say I want to add the ticker for the stock Nvidia, and now that a pin function adds Nvidia to the end of my tech portfolio list. So if I print the list now you can see that Nvidia has been added at the very end.
In the exact same way you can use the remove function to remove an object from your list. And the formatting is going to be exactly the same as the append function. So take my tech portfolio list and then I'm gonna write dot remove, open parentheses, and then I'm gonna type the object that I want to remove. So let's say that I wanna take Amazon out of my portfolio.
Now when I print it, you can see Amazon has been removed from the list.