0

copy in Python

Is "import copy" necessary in python while we are copying a tuple. Example-1: import copy old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] new_list = copy.copy(old_list) Example-2: old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] new_list =old_list.copy() Both example 1 and 2 is working.

1st Jun 2019, 11:40 PM
harshit
harshit - avatar
6 Antworten
+ 2
1. AttributeError: 'tuple' object has no attribute 'copy'. 2. list.copy() and dict.copy() are built-in functions for shallow copies. They're available since Python 3.4. 3. copy.copy() can also copy functions and classes.
2nd Jun 2019, 2:50 AM
Diego
Diego - avatar
+ 1
harshit I was talking about the original question. "Is 'import copy' necessary in Python while we are copying a tuple?"
2nd Jun 2019, 4:56 PM
Diego
Diego - avatar
0
Diego in point number 1, why we use tuple ? It is not mutable so using copy doesn't make sense ?
2nd Jun 2019, 3:12 PM
harshit
harshit - avatar
0
Kishalaya Saha please see this
3rd Jun 2019, 9:02 AM
harshit
harshit - avatar
0
Sorry, I'm not sure what you're confused about. It seems your questions have already been answered. Anyway, tuples might contain nested lists as elements, and those guys could be changed. So a deep copy might be necessary sometimes.
3rd Jun 2019, 11:17 AM
Kishalaya Saha
Kishalaya Saha - avatar