
Table of Contents(目次)
Copying a list to another variable
First, let’s assign the data of a list to another variable. Write the following code and check the output.
original_list = [1, 2, 3]
copied_list = original_list
print(f'original: {original_list}') # [1, 2, 3]
print(f'copied: {copied_list}') # [1, 2, 3] The copied list has the same content as the original
The code above tries to copy the list assigned to the variable 'original_list' into the variable 'copied_list'. The print output looks the same.
Next, let’s modify an element of the copied list. Write the following code and check the output.
original_list = [1, 2, 3]
copied_list = original_list
copied_list[0] = 99
print(f'original_list: {original_list}') # [99, 2, 3] The original list is also changed
print(f'copied_list: {copied_list}') # [99, 2, 3] The copied list is changed as well
The result shows that both the original list and the copied list have been modified. Why does this happen? The reason will be explained in the next lecture, but for now, let’s look at one solution.
You can use slicing ([:]
) to make a copy, as shown below. Run the code and check the result.
original_list = [1, 2, 3]
copied_list = original_list[:]
copied_list[0] = 99
print(f'original_list: {original_list}') # [1, 2, 3] The original list is not changed
print(f'copied_list: {copied_list}') # [99, 2, 3] Only the copied list is changed
When you run the code above, you can see that the original list remains unchanged while only the copied list is modified. When using slicing, Python extracts the content of the original list for the specified range and creates a new list. Therefore, the original list and the copied list are separate data, and modifying one will not affect the other.
Copying a nested list to another variable
Next, let’s check how copying works with nested lists.
original_list = [[1, 2], 3, 4]
copied_list = original_list[:]
copied_list[0] = 99
print(f'original_list: {original_list}') # [[1, 2], 3, 4] The original list is not changed
print(f'copied_list: {copied_list}') # [99, 3, 4] The copied list is changed
The code above copies a nested list using slicing. Changing the value of the nested element ([0]
) does not seem to affect the original list.
Now, let’s try modifying an element inside the list at index [0]
([1, 2]
). Run the following code and check the result.
original_list = [[1, 2], 3, 4]
copied_list = original_list[:]
copied_list[0][0] = 99
print(f'original_list: {original_list}') # [[99, 2], 3, 4] The original list is also changed
print(f'copied_list: {copied_list}') # [[99, 2], 3, 4] The copied list is also changed
If you modify an element inside the nested list ([0][0]
), the original list is changed as well.
As it stands, modifying an element inside "copied_list" still affects the original list. To solve this issue, it is necessary to understand how Python manages variables and data. In the next lecture, we will provide a detailed explanation of Python’s variables and data management.