From 9b2157734305925da484d682423d614fcb485e62 Mon Sep 17 00:00:00 2001 From: NashMiao Date: Fri, 19 Oct 2018 14:57:36 +0800 Subject: [PATCH 1/2] Update README.md add an example about apply reverse operation to an assign variable may cause unexpected error. --- README.md | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/README.md b/README.md index d9b9563..441febf 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ So, here we go... - [▶ Yes, it exists!](#-yes-it-exists) - [▶ Inpinity *](#-inpinity-) - [▶ Mangling time! *](#-mangling-time-) + - [▶ Reverse all! *](#-reverse-all-) - [Section: Miscellaneous](#section-miscellaneous) - [▶ `+=` is faster](#--is-faster) - [▶ Let's make a giant string!](#-lets-make-a-giant-string) @@ -2133,6 +2134,59 @@ Why did `Yo()._Yo__honey` work? Only Indian readers would understand. --- +### ▶ Reverse all! * + +```py +>>> a = bytearry('1234567890') +>>> b = a +>>> a +bytearray(b'1234567890') +>>> b +bytearray(b'1234567890') +>>> b.reverse() +>>> b +bytearray(b'0987654321') +>>> a +bytearray(b'0987654321') +``` + +I just want to reverse `b`, but `a` is also reversed! + +```py +>>> aList = ['a', 'b', 'c', 'd', 'e'] +>>> bList = aList +>>> aList +['a', 'b', 'c', 'd', 'e'] +>>> bList +['a', 'b', 'c', 'd', 'e'] +>>> bList.reverse() +>>> bList +['e', 'd', 'c', 'b', 'a'] +>>> aList +['e', 'd', 'c', 'b', 'a'] +``` + +I just want to reverse `bList`, but `aList` is also reversed! + +#### 💡 Explanation: + +* In Python, Assignment statements in Python do not copy objects, they create bindings between a target and an object. +* If we want apply an new memory for our new variable, we need to use `copy.copy(x)` to execute shallow copying or `copy.deepcopy(x)` to execute deep copying. + +```py +>>> a = bytearray(b'1234567890') +>>> b = a.copy() +>>> a +bytearray(b'1234567890') +>>> b +bytearray(b'1234567890') +>>> b.reverse() +>>> b +bytearray(b'0987654321') +>>> a +bytearray(b'1234567890') +``` + --- ## Section: Miscellaneous From 96173fb19e34da696f6078b20337d5112a7ba008 Mon Sep 17 00:00:00 2001 From: NashMiao <18191964+NashMiao@users.noreply.github.com> Date: Mon, 18 Mar 2019 19:32:42 +0800 Subject: [PATCH 2/2] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 441febf..de80abd 100644 --- a/README.md +++ b/README.md @@ -2137,7 +2137,7 @@ Why did `Yo()._Yo__honey` work? Only Indian readers would understand. ### ▶ Reverse all! * ```py ->>> a = bytearry('1234567890') +>>> a = bytearray('1234567890') >>> b = a >>> a bytearray(b'1234567890')