DEV Community

VIDHYA VARSHINI
VIDHYA VARSHINI

Posted on • Edited on

Day 5 of Python(Tuple, Deep copy and Shallow copy)

What is tuple: It is a collection of items which is ordered, immutable and allows duplicates. This can also store different data types. A tuple can be identified when it is separated by a comma and no need of bracket.

Ex:

 num = 1,2,3,4,5,6
 print(num[2:5])
 print(num[3])
Enter fullscreen mode Exit fullscreen mode

Output:

(3, 4, 5)
4
Enter fullscreen mode Exit fullscreen mode

Single tuple: A tuple with only one item is called a single tuple.
Ex:

num = (1,)
print(type(num))

Enter fullscreen mode Exit fullscreen mode

Output:

<class 'tuple'>
Enter fullscreen mode Exit fullscreen mode

Deep copy: This creates a completely new copy of an object including all nested objects inside it.

Ex:

import copy
a = [[1, 2], [89, 4]]   
b = copy.deepcopy(a)       
b[1][0] = 98


print( a)
print(b)
Enter fullscreen mode Exit fullscreen mode

Output:

[[1, 2], [89, 4]]
[[1, 2], [98, 4]]

Enter fullscreen mode Exit fullscreen mode

Shallow copy: This creates a new outer object, but does not copy nested objects. Instead, it copies reference to them.

Ex:

import copy
a = [[1, 2], [89, 4]]   
b = copy.copy(a)       
b[1][0] = 98


print( a)
print(b)
Enter fullscreen mode Exit fullscreen mode

Output:

[[1, 2], [98, 4]]
[[1, 2], [98, 4]]

Enter fullscreen mode Exit fullscreen mode

Top comments (0)