Change Elements in a List
So you may be thinking, why do I even want to work with lists? Well, the thing is you can change elements in the list, and that’s pretty exciting. If you look at this code example, you can see that we’re using the
numbers list again.
And instead of throwing an error, when you try to assign a new value to an index position in the list, it just does it. So the resulting list after this short piece of code where you start with the list
[1, 2, 3], and then change the element at index one to
20 is that you have a list that contains the integer
1, the integer
20, and the integer
01:47 Is that exciting? Well, it gets even better. The size of your list isn’t fixed, so it can grow and shrink as well. After creation, you can go in there and for example, use slice notation to select, let’s say we’re going to select starting from index one and going all the way to the end.
And just as if nothing happened, we mutated the list
numbers back to its original shape. You can see like you went through quite a few steps, you addressed one specific element in the list and changed its value.
You grew the list by assigning more elements to a slice of fewer elements. So in this case, it was you got a slice of two elements,
3, and you replaced it with a list of three elements, which effectively grew the list by one element.
04:20 This is why lists are pretty powerful because of their flexibility. You can basically create a structure, a collection of elements, that you can throughout the course of your program change as much as you want to.
Become a Member to join the conversation.