Lesson 05-05: Duplicating Lists

Learning Target: I can duplicate a list.

Algorithm for Duplicating

In order to write a function to modify a list without affecting the original one, we would need to make a copy of it. Although there are shortcuts to make copies of lists, let’s first see how we might do it manually.

We want to start by creating a new, blank list. This ensures that it will have a different reference than the one we’re trying to copy.

old_list = [1,2,3,4]
new_list = [] #this is an empty list

Then we need to manually loop through the old array and ‘copy’ every element into the new array. We can do this by using append(). We can then look at the IDs and check if they are equal to each other using the following code:

Using the copy.copy() Function

Python also has a built-in copy library that has a bunch of functions related to copying things. We can use the copy.copy() function to make a quick copy of a list.

As you can see, this much easier - but it’s important to know how to copy lists anyway!

Next Section - Lesson 05-06: Building List Functions: extend