Sunday, December 24, 2017

Manipulating Python Lists

Changing list elements is pretty straightforward. You use the same square brackets that we've used to subset lists, and then assign new elements to it using the equals sign.

To change this list element, which is at index 7, you can use this line:
To change the elements "liz" and 1.73, you access the first two elements with zero colon 2, and then assign a new list to it.
If you use the plus sign with two lists, Python simply pastes together their contents in a single list. 
Of course, you can also store this new list in a variable, `fam_ext` for example.
Finally, deleting elements from a list is also pretty straightforward; you'll have to use `del` here. Take this line, for example, that deletes the element with index 2.

Understanding how Python lists actually work behind the scenes becomes pretty important
What actually happens when you create a new list, `x`, like this?
Well, in a simplified sense, you're storing a list in your computer memory, and store the 'address' of that list, so where the list is in your computer memory, in `x`. This means that `x` does not actually contain all the list elements, it rather contains a reference to the list.
Let's store the list `x` as a new variable `y`, by simply using the equals sign:
Let's now change the element with index one in the list `y`, as follows:
The funky thing is that if you now check out `x` again, also here the second element was changed
That's because when you copied x to y with the equals sign, you copied the reference to the list, not the actual values themselves. 

When you're updating an element the list, though, it's one and the same list in the computer memory you are changing.

Both `x` and `y` point to this list, so the update is visible from both.
If you want to create a list `y` that points to a new list in the memory with the same variables, you'll need to use something else than the equals sign. You can use the `list()` function, like this, or use slicing to select all list elements explicitly.

If you now make a change to the list `y` points to, `x` is not affected:


Post a Comment


Talk to us (+91-9738925800)