Copy() method of deque class in Python

Method Name:

copy

 

Method Signature:

copy

 

Method Overview:

  • copy() method of deque class in python returns copy of a deque object.

 

  • The returned deque object is a new object where as the elements present in the new deque object are just copied from the original deque. ie., elements are shallow copied

 

  • The example below verifies the shallow copying process of the copy() method by printing the id of the deque objects as well as an element present in the deque objects.

 

Example:

import collections

 

t1 = (1,2,3,4,5)

d1 = collections.deque(t1)

d2 = d1.copy()

 

print("d1 contents:")

print(d1)

print("d2 id:")

print(id(d1))

 

 

print("d2 contents:")

print(d2)

print("d2 id:")

print(id(d2))

 

 

print("checking the first element of d1 and d2 are shallow copies:")

print(id(d1[0]))

print(id(d2[0]))

 

Output:

d1 contents:

deque([1, 2, 3, 4, 5])

d2 id:

4300761504

d2 contents:

deque([1, 2, 3, 4, 5])

d2 id:

4301821744

checking the first element of d1 and d2 are shallow copies:

4297623936

4297623936

 


Copyright 2024 © pythontic.com