Guest User

Untitled

a guest
Jan 16th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.22 KB | None | 0 0
  1. new_list = old_list[:]
  2.  
  3. new_list = list(old_list)
  4.  
  5. import copy
  6. new_list = copy.copy(old_list)
  7.  
  8. import copy
  9. new_list = copy.deepcopy(old_list)
  10.  
  11. import copy
  12.  
  13. class Foo(object):
  14. def __init__(self, val):
  15. self.val = val
  16.  
  17. def __repr__(self):
  18. return str(self.val)
  19.  
  20. foo = Foo(1)
  21.  
  22. a = ['foo', foo]
  23. b = a[:]
  24. c = list(a)
  25. d = copy.copy(a)
  26. e = copy.deepcopy(a)
  27.  
  28. # edit orignal list and instance
  29. a.append('baz')
  30. foo.val = 5
  31.  
  32. print('original: %rn slice: %rn list(): %rn copy: %rn deepcopy: %r'
  33. % (a, b, c, d, e))
  34.  
  35. original: ['foo', 5, 'baz']
  36. slice: ['foo', 5]
  37. list(): ['foo', 5]
  38. copy: ['foo', 5]
  39. deepcopy: ['foo', 1]
  40.  
  41. from copy import deepcopy
  42.  
  43. class old_class:
  44. def __init__(self):
  45. self.blah = 'blah'
  46.  
  47. class new_class(object):
  48. def __init__(self):
  49. self.blah = 'blah'
  50.  
  51. dignore = {str: None, unicode: None, int: None, type(None): None}
  52.  
  53. def Copy(obj, use_deepcopy=True):
  54. t = type(obj)
  55.  
  56. if t in (list, tuple):
  57. if t == tuple:
  58. # Convert to a list if a tuple to
  59. # allow assigning to when copying
  60. is_tuple = True
  61. obj = list(obj)
  62. else:
  63. # Otherwise just do a quick slice copy
  64. obj = obj[:]
  65. is_tuple = False
  66.  
  67. # Copy each item recursively
  68. for x in xrange(len(obj)):
  69. if type(obj[x]) in dignore:
  70. continue
  71. obj[x] = Copy(obj[x], use_deepcopy)
  72.  
  73. if is_tuple:
  74. # Convert back into a tuple again
  75. obj = tuple(obj)
  76.  
  77. elif t == dict:
  78. # Use the fast shallow dict copy() method and copy any
  79. # values which aren't immutable (like lists, dicts etc)
  80. obj = obj.copy()
  81. for k in obj:
  82. if type(obj[k]) in dignore:
  83. continue
  84. obj[k] = Copy(obj[k], use_deepcopy)
  85.  
  86. elif t in dignore:
  87. # Numeric or string/unicode?
  88. # It's immutable, so ignore it!
  89. pass
  90.  
  91. elif use_deepcopy:
  92. obj = deepcopy(obj)
  93. return obj
  94.  
  95. if __name__ == '__main__':
  96. import copy
  97. from time import time
  98.  
  99. num_times = 100000
  100. L = [None, 'blah', 1, 543.4532,
  101. ['foo'], ('bar',), {'blah': 'blah'},
  102. old_class(), new_class()]
  103.  
  104. t = time()
  105. for i in xrange(num_times):
  106. Copy(L)
  107. print 'Custom Copy:', time()-t
  108.  
  109. t = time()
  110. for i in xrange(num_times):
  111. Copy(L, use_deepcopy=False)
  112. print 'Custom Copy Only Copying Lists/Tuples/Dicts (no classes):', time()-t
  113.  
  114. t = time()
  115. for i in xrange(num_times):
  116. copy.copy(L)
  117. print 'copy.copy:', time()-t
  118.  
  119. t = time()
  120. for i in xrange(num_times):
  121. copy.deepcopy(L)
  122. print 'copy.deepcopy:', time()-t
  123.  
  124. t = time()
  125. for i in xrange(num_times):
  126. L[:]
  127. print 'list slicing [:]:', time()-t
  128.  
  129. t = time()
  130. for i in xrange(num_times):
  131. list(L)
  132. print 'list(L):', time()-t
  133.  
  134. t = time()
  135. for i in xrange(num_times):
  136. [i for i in L]
  137. print 'list expression(L):', time()-t
  138.  
  139. t = time()
  140. for i in xrange(num_times):
  141. a = []
  142. a.extend(L)
  143. print 'list extend:', time()-t
  144.  
  145. t = time()
  146. for i in xrange(num_times):
  147. a = []
  148. for y in L:
  149. a.append(y)
  150. print 'list append:', time()-t
  151.  
  152. t = time()
  153. for i in xrange(num_times):
  154. a = []
  155. a.extend(i for i in L)
  156. print 'generator expression extend:', time()-t
  157.  
  158. a_copy = a_list.copy()
  159.  
  160. a_copy = a_list[:]
  161.  
  162. a_copy = a_list[:]
  163.  
  164. a_copy = list(a_list)
  165.  
  166. >>> timeit
  167. >>> l = range(20)
  168. >>> min(timeit.repeat(lambda: l[:]))
  169. 0.30504298210144043
  170. >>> min(timeit.repeat(lambda: list(l)))
  171. 0.40698814392089844
  172.  
  173. a_copy = a_list.copy()
  174.  
  175. >>> import timeit
  176. >>> l = list(range(20))
  177. >>> min(timeit.repeat(lambda: l[:]))
  178. 0.38448613602668047
  179. >>> min(timeit.repeat(lambda: list(l)))
  180. 0.6309100328944623
  181. >>> min(timeit.repeat(lambda: l.copy()))
  182. 0.38122922903858125
  183.  
  184. >>> l = [[], [], []]
  185. >>> l_copy = l[:]
  186. >>> l_copy
  187. [[], [], []]
  188. >>> l_copy[0].append('foo')
  189. >>> l_copy
  190. [['foo'], [], []]
  191. >>> l
  192. [['foo'], [], []]
  193.  
  194. import copy
  195. a_deep_copy = copy.deepcopy(a_list)
  196.  
  197. >>> import copy
  198. >>> l
  199. [['foo'], [], []]
  200. >>> l_deep_copy = copy.deepcopy(l)
  201. >>> l_deep_copy[0].pop()
  202. 'foo'
  203. >>> l_deep_copy
  204. [[], [], []]
  205. >>> l
  206. [['foo'], [], []]
  207.  
  208. problematic_deep_copy = eval(repr(a_list))
  209.  
  210. >>> import timeit
  211. >>> import copy
  212. >>> l = range(10)
  213. >>> min(timeit.repeat(lambda: copy.deepcopy(l)))
  214. 27.55826997756958
  215. >>> min(timeit.repeat(lambda: eval(repr(l))))
  216. 29.04534101486206
  217.  
  218. >>> import timeit
  219. >>> import copy
  220. >>> l = list(range(10))
  221. >>> min(timeit.repeat(lambda: copy.deepcopy(l)))
  222. 16.84255409205798
  223. >>> min(timeit.repeat(lambda: eval(repr(l))))
  224. 34.813894678023644
  225.  
  226. new_list = list(my_list) # or my_list[:], but I prefer this syntax
  227. # is simply a shorter way of:
  228. new_list = [element for element in my_list]
  229.  
  230. import copy
  231. # each element must have __copy__ defined for this...
  232. new_list = [copy.copy(element) for element in my_list]
  233.  
  234. import copy
  235. # each element must have __deepcopy__ defined for this...
  236. new_list = copy.deepcopy(my_list)
  237.  
  238. >>> a = [1,2]
  239. >>> b = a[:]
  240. >>> a += [3]
  241. >>> a
  242. [1, 2, 3]
  243. >>> b
  244. [1, 2]
  245. >>>
  246.  
  247. new_list = eval(repr(old_list))
  248.  
  249. old_list = [[0 for j in range(y)] for i in range(x)] # initialize (x,y) nested list
  250.  
  251. # assign a copy of old_list to new list without them pointing to the same list object
  252. new_list = eval(repr(old_list))
  253.  
  254. # make a change to new_list
  255. for j in range(y):
  256. for i in range(x):
  257. new_list[i][j] += 1
  258.  
  259. >>> new_list
  260.  
  261. [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
  262.  
  263. >>> old_list
  264.  
  265. [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
  266.  
  267. METHOD TIME TAKEN
  268. b = a[:] 6.468942025996512 #Python2 winner
  269. b = a.copy() 6.986593422974693 #Python3 "slice equivalent"
  270. b = []; b.extend(a) 7.309216841997113
  271. b = a[0:len(a)] 10.916740721993847
  272. *b, = a 11.046738261007704
  273. b = list(a) 11.761539687984623
  274. b = [i for i in a] 24.66165203397395
  275. b = copy.copy(a) 30.853400873980718
  276. b = []
  277. for item in a:
  278. b.append(item) 48.19176080400939
  279.  
  280. import timeit
  281.  
  282. COUNT = 50000000
  283. print("Array duplicating. Tests run", COUNT, "times")
  284. setup = 'a = [0,1,2,3,4,5,6,7,8,9]; import copy'
  285.  
  286. print("b = list(a)tt", timeit.timeit(stmt='b = list(a)', setup=setup, number=COUNT))
  287. print("b = copy.copy(a)tt", timeit.timeit(stmt='b = copy.copy(a)', setup=setup, number=COUNT))
  288. print("b = a.copy()tt", timeit.timeit(stmt='b = a.copy()', setup=setup, number=COUNT))
  289. print("b = a[:]tt", timeit.timeit(stmt='b = a[:]', setup=setup, number=COUNT))
  290. print("b = a[0:len(a)]t", timeit.timeit(stmt='b = a[0:len(a)]', setup=setup, number=COUNT))
  291. print("*b, = at", timeit.timeit(stmt='*b, = a', setup=setup, number=COUNT))
  292. print("b = []; b.extend(a)t", timeit.timeit(stmt='b = []; b.extend(a)', setup=setup, number=COUNT))
  293. print("b = []nfor item in a: b.append(item)t", timeit.timeit(stmt='b = []nfor item in a: b.append(item)', setup=setup, number=COUNT))
  294. print("b = [i for i in a]t", timeit.timeit(stmt='b = [i for i in a]', setup=setup, number=COUNT))
  295.  
  296. a=[1,2,3]
  297.  
  298. b=a
  299.  
  300. list_1=['01','98']
  301. list_2=[['01','98']]
  302.  
  303. copy=list_1
  304.  
  305. The id() function shows us that both variables point to the same list object, i.e. they share this object.
  306.  
  307. print(id(copy))
  308. print(id(list_1))
  309.  
  310. 4329485320
  311. 4329485320
  312.  
  313. copy[0]="modify"
  314.  
  315. print(copy)
  316. print(list_1)
  317.  
  318. ['modify', '98']
  319. ['modify', '98']
  320.  
  321. copy_1=list_1[:]
  322.  
  323. print(id(copy_1))
  324. print(id(list_1))
  325.  
  326. 4338792136
  327. 4338791432
  328.  
  329. copy_1[0]="modify"
  330.  
  331. print(list_1)
  332. print(copy_1)
  333.  
  334. ['01', '98']
  335. ['modify', '98']
  336.  
  337. copy_2=list_2[:]
  338.  
  339. print(id((list_2)),id(copy_2))
  340.  
  341. 4330403592 4330403528
  342.  
  343. copy_2[0][1]="modify"
  344.  
  345. print(list_2,copy_2)
  346.  
  347. [['01', 'modify']] [['01', 'modify']]
  348.  
  349. copy_2=list_2[:]
  350.  
  351. print(id(copy_2[0]))
  352. print(id(list_2[0]))
  353.  
  354. 4329485832
  355. 4329485832
  356.  
  357. from copy import deepcopy
  358. deep=deepcopy(list_2)
  359.  
  360. print(id((list_2)),id(deep))
  361.  
  362. 4322146056 4322148040
  363.  
  364. print(id(deep[0]))
  365. print(id(list_2[0]))
  366.  
  367. 4322145992
  368. 4322145800
  369.  
  370. deep[0][1]="modify"
  371. print(list_2,deep)
  372.  
  373. [['01', '98']] [['01', 'modify']]
  374.  
  375. a = {'par' : [1,21,3], 'sar' : [5,6,8]}
  376. b = a
  377. c = a.copy()
  378. a['har'] = [1,2,3]
  379.  
  380. a
  381. Out[14]: {'har': [1, 2, 3], 'par': [1, 21, 3], 'sar': [5, 6, 8]}
  382.  
  383. b
  384. Out[15]: {'har': [1, 2, 3], 'par': [1, 21, 3], 'sar': [5, 6, 8]}
  385.  
  386. c
  387. Out[16]: {'par': [1, 21, 3], 'sar': [5, 6, 8]}
  388.  
  389. new_list = my_list[:]
  390.  
  391. new_list = my_list * 1 #Solution 1 when you are not using nested lists
  392.  
  393. import copy
  394. new_list = copy.deepcopy(my_list) #Solution 2 when you are using nested lists
  395.  
  396. new_list = my_list[:]
  397.  
  398. >>> a = range(5)
  399. >>> b = a*1
  400. >>> a,b
  401. ([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])
  402. >>> a[2] = 55
  403. >>> a,b
  404. ([0, 1, 55, 3, 4], [0, 1, 2, 3, 4])
  405.  
  406. >>> from copy import deepcopy
  407. >>> a = [range(i,i+4) for i in range(3)]
  408. >>> a
  409. [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
  410. >>> b = a*1
  411. >>> c = deepcopy(a)
  412. >>> for i in (a, b, c): print i
  413. [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
  414. [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
  415. [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]]
  416. >>> a[2].append('99')
  417. >>> for i in (a, b, c): print i
  418. [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5, 99]]
  419. [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5, 99]] #Solution#1 didn't work in nested list
  420. [[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]] #Solution #2 - DeepCopy worked in nested list
  421.  
  422. newlist=list(oldlist)
Add Comment
Please, Sign In to add comment