Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Set clear() method



The Python Setclear() method is used to remove all elements from a set effectively making it an empty set. This method does not take any arguments and modifies the set in place. It is particularly useful when we want to reuse an existing set without retaining its previous elements.

Syntax

Following is the syntax and parameters of Python Setclear() method.

set_name.clear()

Parameter

This method does not take any parameters.

Return value

This method This function returns an empty set.

Example 1

Following is the example of theclear() method which clears the given set and prints the empty set −

# initialzing a setnumber_set = {1, 2, 3, 4, 5}# clearing the setnumber_set.clear()# printing the setprint(number_set)

Output

set()

Example 2

In below example we are creating a set by adding elements into it and later on we used the clear() function to clear the set −

# Creating a setnumbers = {1, 2, 3, 4, 5}# Adding more elementsnumbers.update([6, 7, 8])print(numbers) # Clearing the setnumbers.clear()print(numbers)

Output

{1, 2, 3, 4, 5, 6, 7, 8}set()

Example 3

Now, in here we are using the clear() method in a loop for clearing the elements of the set.

# Creating a list of setslist_of_sets = [{1, 2}, {3, 4}, {5, 6}]# Clearing each set in the listfor s in list_of_sets:    s.clear()print(list_of_sets)

Output

[set(), set(), set()]

Example 4

We can clear the elements in the set based on the given condition and here is the example which clears the set based on the condition where the length of the cities is greater than 2.

# Creating a setcities = {'New York', 'London', 'Paris'}# Conditional clearingif len(cities) > 2:    cities.clear()print(cities)

Output

set()
python_set_methods.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp