Hướng dẫn dùng copy list python

Trong bài này ta sẽ tìm hiểu phương thức list copy() trong Python, phương thức này có công dụng trả về một bản sao thô của List.

Hướng dẫn dùng copy list python

Hướng dẫn dùng copy list python

Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

1. Cú pháp list copy()

Trước tiên bạn hãy xem cú pháp của phương thức này.

Phương thức này không có tham số truyền vào, nhiệm vụ của nó đơn giản chỉ là trả về một bản sao của list, nên thiết nghĩ liệu nó có cần thiết không? Rất cần thiết bởi vì ý nghĩa của nó là trả về một bản sao thô, tức là mọi thay đổi ở bản sao sẽ không ảnh hưởng tới bản gốc.

Giá trị trả về: Trả về list hiện tại.

Hãy thử nghiệm với một ví dụ về việc copy nhưng bằng toán tử = nhé.

Bài viết này được đăng tại [free tuts .net]

old_list = [1, 2, 3]
new_list = old_list

# add element to list
new_list.append('a')

print('New List:', new_list )
print('Old List:', old_list )

Nếu chạy chương trình này thì cả new_list à old_list đều thay đổi, bởi vì cả hai đều trỏ đến cùng một địa chỉ trên bộ nhớ. Kết quả như sau:

Old List: [1, 2, 3, 'a']
New List: [1, 2, 3, 'a']

Nếu bạn muốn khi thay đổi ở old_list mà không ảnh hưởng tới new_list thì sử dụng phương thức copy.

old_list = [1, 2, 3]
new_list = old_list.copy()

# add element to list
new_list.append('a')

print('New List:', new_list )
print('Old List:', old_list )

Chạy lên kết quả sẽ như sau:

New List: [1, 2, 3, 'a']
Old List: [1, 2, 3]

2. Ví dụ với list copy()

Sau đây là một ví dụ khác với phương thức này.

# mixed list
list = ['cat', 0, 6.7]

# copying a list
new_list = list.copy()

# Adding element to the new list
new_list.append('dog')

# Printing new and old list
print('Old List: ', list)
print('New List: ', new_list)

Kết quả:

Old List: ['cat', 0, 6.7]
New List: ['cat', 0, 6.7, 'dog']

Ngoài ra bạn cũng có thể sử dụng toán tử Slicing để copy một list.

# mixed list
list = ['cat', 0, 6.7]

# copying a list using slicing
new_list = list[:]

# Adding element to the new list
new_list.append('dog')

# Printing new and old list
print('Old List: ', list)
print('New List: ', new_list)

Chạy lên kết quả vẫn như trên.

Copy a list trong Python


Hôm nay ta sẽ học cách copy 1 list trong python. Ta xem đoạn code bên dưới.

my_list1 = [1,2,3]

copy_list1 = my_list1  # gán my_list1 vào copy_list1
copy_list1[0] = "Copy"  # thay đổi giá trị

print(copy_list1)  # ["Copy",2,3]  # copy_list1 thay đổi
print(my_list1)  # ["Copy",2,3]  
# my_list1 cũng thay đổi. Vậy tại sao my_list1 thay đổi theo.

Ta thấy my_list1 thay đổi theo chứng tỏ cả my_list1 và copy_list1 đều cùng trỏ về cùng 1 giá trị. Ta thử kiểm tra xem my_list1 và copy_list1 có phải trỏ về cùng 1 giá trị hay không.

print(my_list1 is copy_list1)  # True

Vậy thì ta thấy my_list1 và copy_list1 thực chất là 1. Vậy làm sao để copy một list trong Python?. Ta dùng cách sau.

my_list2 = [1,2,3]

copy_list2 = my_list2[:]  
# my_list2[:] lấy hết các phần tử của my_list2
# và tạo ra 1 list mới gán vào copy_list2

copy_list2[0] = "Copy"
print(copy_list2)  # ["Copy",2,3]
print(my_list2)  # [1,2,3]

print(my_list2 is copy_list2)  # False

Như vậy để copy 1 list trong Python ta dùng my_list2[:].

Ngoài ra để lấy ra 1 số phần tử của list ta làm tương tự.

my_list3 = [1,2,3,4]

# lấy ra index 1 tới index 2
new_list = my_list3[1:3]  
# new_list có giá trị là [2,3] , my_list3 giá trị không đổi
print(new_list)

# lấy ra từ index 1 tới cuối
new_list2 = my_list3[1:]  # [2,3,4]
print(new_list2)

# lấy tất cả phần tử bỏ phần tử cuối
new_list3 = my_list3[0:-1] # [1,2,3]
print(new_list3)

# copy hết 
new_list4 = my_list3[:]
print(new_list4)  # [1,2,3,4]

Như vậy ta đã biết cách copy 1 list trong Python rồi nhé. ^_^

Let us see how to copy arrays in Python. There are 3 ways to copy arrays : 

  • Simply using the assignment operator.
  • Shallow Copy
  • Deep Copy

Assigning the Array

We can create a copy of an array by using the assignment operator (=). 

Syntax : 

new_arr = old_ arr

In Python, Assignment statements do not copy objects, they create bindings between a target and an object. When we use = operator user thinks that this creates a new object; well, it doesn’t. It only creates a new variable that shares the reference of the original object.

Example:

Python3

from numpy import *                  

arr1 = array([2, 6, 9, 4])            

print(id(arr1))

arr2 = arr1                         

print(id(arr2))

arr1[1] = 7                        

print(arr1)

print(arr2)

Output : 

117854800
117854800
[2 7 9 4]
[2 7 9 4]

We can see that both the arrays reference the same object. 

Shallow Copy

A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original. The copying process does not recurse and therefore won’t create copies of the child objects themselves. In the case of shallow copy, a reference of the object is copied in another object. It means that any changes made to a copy of the object do reflect in the original object. We will be implementing shallow copy using the view() function.

Example : 

Python3

from numpy import *                 

arr1 = array([2, 6, 9, 4])

print(id(arr1))

arr2 = arr1.view() 

print(id(arr2))

arr1[1] = 7                       

print(arr1)

print(arr2)

This time although the 2 arrays reference different objects, still on changing the value of one, the value of another also changes.

Deep Copy

Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of the object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object. We will be implementing deep copy using the copy() function.

Python3

from numpy import *                 

arr1 = array([2, 6, 9, 4])

print(id(arr1))

arr2 = arr1.copy()

print(id(arr2))

arr1[1] = 7                       

print(arr1)

print(arr2)

Output : 

121258976
125714048
[2 7 9 4]
[2 6 9 4]

This time the changes made in one array are not reflected in the other array.

Deep Copy Continued

If you are dealing with NumPy matrices, then numpy.copy() will give you a deep copy. However, if your matrix is simply a list of lists then consider the below two approaches in the task of rotating an image (represented as a list of a list) 90 degrees:

Python3

import copy

def rotate_matrix(image):

    copy_image_one = copy.deepcopy(image)

    print("Original", matrix)

    print("Copy of original", copy_image_one)

    N = len(matrix)

    for row in range(N):

        for column in range(N):

            copy_image_one[row][column] = image[row][N-column-1]

    print("After modification")

    print("Original", matrix)

    print("Copy", copy_image_one)

    copy_image_two = [list(row) for row in copy_image_one]

    for row in range(N):

        for column in range(N):

            copy_image_two[column][row] = copy_image_one[row][column]

    return copy_image_two

if __name__ == "__main__":

    matrix = [[1, 2, 3],

              [4, 5, 6],

              [7, 8, 9]]

    print("Rotated image", rotate_matrix(matrix))

Output:

Original [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Copy of original [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
After modification
Original [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Copy [[3, 2, 1], [6, 5, 4], [9, 8, 7]]
Rotated image [[3, 6, 9], [2, 5, 8], [1, 4, 7]]