Copying Lists¶
Assume that var1
is a variables of type int
, float
, str
, or bool
. We have seen before that if we create a new variable var2
and set its initial value to be equal to that of var1
, then var2
will initially contain the same value as var1
, but will be its own distinct variable whose value can be changed independent of var1
. This is illustrated in the following two cells.
var1 = 37
var2 = var1
print(var1)
print(var2)
37
37
var2 = "blah"
print(var1)
print(var2)
37
blah
The situation is different for lists, however. If we have a list called list1
and we set list2
to be equal to list1
, then list1
and list2
will be two different names of the same list. Any changes made to list1
will also effect list2
and vice versa.
list1 = [3, 8, 2]
list2 = list1
print(list1)
print(list2)
[3, 8, 2]
[3, 8, 2]
list2.append(37)
print(list1)
print(list2)
[3, 8, 2, 37]
[3, 8, 2, 37]
What if we want to actually create a new, entirely separate, copy of an already existing list? It turns out that Python provides two ways of doing a such.
We may use the
copy()
method of the list that we wish to duplicate.We can return a copy of a list by using slicing.
Let’s see first see how to duplicate a list using the copy()
method.
dup1 = list1.copy()
print(list1)
print(dup1)
[3, 8, 2, 37]
[3, 8, 2, 37]
dup1.append(42)
print(list1)
print(dup1)
[3, 8, 2, 37]
[3, 8, 2, 37, 42]
We will now see how to duplicate a list by using slicing.
dup2 = list1[:]
print(list1)
print(dup2)
[3, 8, 2, 37]
[3, 8, 2, 37]
dup2.remove(8)
print(list1)
print(dup2)
[3, 8, 2, 37]
[3, 2, 37]
Example: Copying and Sorting Lists¶
A list called Avengers
is provided in the cell below. Add code to accomplish the following tasks:
Create two new copies of the list, one called
Avengers_Asc
and one calledAvengers_Desc
.Sort
Avengers_Asc
in ascending alphabetical order.Sort
Avengers_Desc
in descending alphabetical order.Print all three lists.
Avengers = ['Capt. America', 'Black Widow', 'Iron Man', 'Hulk', 'Thor', 'Hawkeye']
Avengers_Asc = Avengers.copy()
Avengers_Desc = Avengers.copy()
Avengers_Asc.sort()
Avengers_Desc.sort(reverse=True)
print(Avengers)
print(Avengers_Asc)
print(Avengers_Desc)
['Capt. America', 'Black Widow', 'Iron Man', 'Hulk', 'Thor', 'Hawkeye']
['Black Widow', 'Capt. America', 'Hawkeye', 'Hulk', 'Iron Man', 'Thor']
['Thor', 'Iron Man', 'Hulk', 'Hawkeye', 'Capt. America', 'Black Widow']
Avengers_Asc = sorted(Avengers)
Avengers_Desc = sorted(Avengers)
Avengers_Desc.reverse()
print(Avengers)
print(Avengers_Asc)
print(Avengers_Desc)
['Capt. America', 'Black Widow', 'Iron Man', 'Hulk', 'Thor', 'Hawkeye']
['Black Widow', 'Capt. America', 'Hawkeye', 'Hulk', 'Iron Man', 'Thor']
['Thor', 'Iron Man', 'Hulk', 'Hawkeye', 'Capt. America', 'Black Widow']