List are Mutable
Lists are mutable data type. This means that its composition can be altered without recreation, reassignment, redeclaration. This can be dangerous for most new programmers.
Example 1: Altering via index:
In example 1, you can see that we can change the composition of the list without redeclaring a new list for the variable: primes
.
Example 2: Copying a List to another variable:
In example 2, we have only manipulated the list called primes2
. However, the original list called primes1
was also affected by the changes as well.
This is because when a new variable is created to hold another list variable. Python saves memory by pointing towards where the original list is located rather than creating a whole new copy.
Therefore, any changes will affect both variables.
Solution: Use a method called .copy()
This method will help us create a new list in memory with the same values from the original.
Example 3: Sorting & List Methods
List has a built-in method to help sort. Unlike the sorted()
function, list has a method which allows us to manipulate the list you are sorting without creating a whole new variable.
Examine that there is no assignment operation occurring to help us sort. We are using a method that lists have to just manipulate the given list rather than needing to create a new container like strings.
Below are the list of methods that affect the composition of a list. They will not require recreation/reassignment.
append()
extend()
insert()
remove()
pop()
sort()
reverse()
Last updated