Python Set clear() Method
Python Set clear() Method
The set.clear() method removes all the elements from the set.
Syntax
set.clear()
Parameter
NA
Return
None
Example 1
# Python program explaining
# the set.clear() method
# initializing the set
fruits = {"watermelon", "banana", "apple"}
# printing the set
print("Actual set:",fruits)
# clearing off all the elements from the fruits set.
fruits.clear()
print("After the clear() method...")
print("Set:",fruits)
Output
Actual set: {'apple', 'banana', 'watermelon'}
After the clear() method...
Set: set()
Example 2
# Python program explaining
# the set.clear() method
# set of week
week = {'Monday', 'Tuesday', 'Wednesday','Thursday'}
# locating the elements of week in newWeek
newWeek = week
# clearing all the elements
week.clear()
print('Removing all the element using clear() method')
print('Set: ', week)
print('New set: ', newWeek)
# again initializing the set
week = {'Wednesday','Thursday','Friday','Saturday'}
newWeek = week
week = {}
print('Removing all the element by assigning {}')
print('Set: ', week)
print('New Set: ', newWeek)
Output
Removing all the element using clear() method
Set: set()
New set: set()
Removing all the element by assigning {}
Set: {}
New Set: {'Friday', 'Thursday', 'Saturday', 'Wednesday'}
Python Set copy() Method
The set.copy() method in Python copies the set .
Syntax
set.copy()
Parameter
NA
Return
This method returns a shallow copy of the set.
Example 1
# Python program explaining
# the set.copy() method
# initializing the set
fruits = {"watermelon", "banana", "apple"}
# prinitng the set
print("Actual set: ",fruits)
# copying the set elements in new set.
newFruits= fruits.copy()
print("After the copying the dictionary...")
print("Copied set:",newFruits)
Output
Actual set: {'apple', 'banana', 'watermelon'}
After the copying the dictionary...
Copied set: {'apple', 'banana', 'watermelon'}
Example 2
# Python program explaining
# the set.copy() method
vowels = {'a', 'e', 'i', 'o'}
# copying the vowels set to the secondSet
secondSet = vowels.copy()
# before adding
print ('Before adding... ')
print ('firstirst vowels set: ',vowels )
print ('Second vowels set: ', secondSet )
# Adding element to second set, the first set does not change.
secondSet.add('u')
# after adding the last vowel 'u' in the set
print ('After adding... ')
print ('First vowels set: ',vowels )
print ('second vowels set: ', secondSet )
Output
Before adding...
firstirst vowels set: {'e', 'a', 'i', 'o'}
Second vowels set: {'e', 'a', 'i', 'o'}
After adding...
First vowels set: {'e', 'a', 'i', 'o'}
second vowels set: {'e', 'a', 'i', 'o', 'u'}
