More On Data Structures
Last updated
Last updated
Something very important to understand about lists is that they are not simply a single value. They are a collection of values. Each value in a list has a specific address (or index) in the computer's memory. Because of this, when we give lists to functions we might call, the computer does not copy all of the values in the list to a function. Rather, it just gives the function a reference to where those values exist in memory. This can cause some headaches for someone who might not be aware of what is going on. If the function changes the value in the list we gave it without our knowing, then we might be surprised when we try to use the list later on and find that it doesn't have the values we expected.
In the example below we can see the difference between working with values and working with references.
If you were able to follow the above example, you might be wondering why spam and cheese both changed when all we did was change cheese[2]
to equal 'hello'
. The reason is because when we set spam = cheese
we were not copying all of the values from cheese
into a new list called spam
. We were simply giving spam
the location of the first item in cheese
. This is just like a library. What if we were to create a bookshelf and put a bunch of books on it and then create an index card with the name of Fantasy
and an address of 42. We could then simply create a new index card called Romance
and give it the value of Fantasy
which is ... 42. This means that anyone who tries to find Romance
will be led directly to the superior genre of Fantasy
. They might be happier with the selection of books but, unfortunately, they didn't find what they were looking for.
You may be wondering how we can easily make copies of lists and dictionaries. Well, there is a module called copy
that you can import: import copy
. It has two methods called copy()
and deepcopy()
that you can use to copy your lists and dictionaries.
Take a look at the Python documentation on copy and deepcopy for more information about these methods.