Python Set clear() Method

Python Set clear() Method

The set.clear() method removes all the elements from the set.

Syntax

Parameter

NA

Return

None

Example 1

Output

Example 2

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’}