set copy () in python

Python Methods and Functions

Syntax :

  set_name  .copy ()  set_name : Name of the set whose copy we want to generate ... 

Parameters: The copy () method for sets does not take any parameters.

Return value: the function returns a shallow copy of the original set .

Below is the implementation of the above function:

# Python3 program to demonstrate usage
# of join () function

 

set1 = { 1 , 2 , 3 , 4

  
# function to copy the set

< code class = "plain"> set2 = set1.copy () 

 
# prints the copied set

print (set2) 

Output:

 {1, 2, 3, 4} 

Shallow copy example:

# Python program to showcase this copy
# generated from the installed copy small

first = { 'g' , 'e' , ' e' , 'k' , 's' }

second = first.copy ()

 
# before adding

print 'before adding:'

print 'first: ' , first

print ' second: ' , second 

  
# Adding an element to the second, the first one is not
# submit.

second.add ( 'f' )

  
# after adding < / code>

print 'after adding:'

print 'first:' , first

print 'second:' , second 

Output:

 before adding: first: set (['s',' e', ' k', 'g']) second: set ([' s', 'e',' k', 'g']) after adding: first: set ([' s', 'e',' k', 'g']) second: set ([' s', 'e',' k', 'g',' f']) 




Tutorials