Python Set Methods

Python sets provide several built-in methods for adding, removing, and manipulating set items. add() The add() method adds a single item to a set. Syntax Example Output: update() The update() method adds multiple items from another collection. Syntax Example Output: remove() The remove() method removes a specified item. Syntax Example Output: discard() The discard() method […]

2 mins read Lesson 30 of 40 75% through track

Python sets provide several built-in methods for adding, removing, and manipulating set items.

add()

The add() method adds a single item to a set.

Syntax

set_name.add(item)

Example

fruits = {"apple", "banana"}

fruits.add("mango")

print(fruits)

Output:

{'apple', 'banana', 'mango'}

update()

The update() method adds multiple items from another collection.

Syntax

set_name.update(iterable)

Example

fruits = {"apple", "banana"}

fruits.update(["mango", "orange"])

print(fruits)

Output:

{'apple', 'banana', 'mango', 'orange'}

remove()

The remove() method removes a specified item.

Syntax

set_name.remove(item)

Example

fruits = {"apple", "banana", "mango"}

fruits.remove("banana")

print(fruits)

Output:

{'apple', 'mango'}

discard()

The discard() method removes a specified item without raising an error if the item does not exist.

Syntax

set_name.discard(item)

Example

fruits = {"apple", "banana"}

fruits.discard("orange")

print(fruits)

Output:

{'apple', 'banana'}

pop()

The pop() method removes and returns a random item from the set.

Syntax

set_name.pop()

Example

fruits = {"apple", "banana", "mango"}

item = fruits.pop()

print(item)
print(fruits)

Output:

apple
{'banana', 'mango'}

The removed item may vary.

clear()

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

Syntax

set_name.clear()

Example

fruits = {"apple", "banana", "mango"}

fruits.clear()

print(fruits)

Output:

set()

copy()

The copy() method creates a copy of a set.

Syntax

set_name.copy()

Example

fruits = {"apple", "banana"}

new_fruits = fruits.copy()

print(new_fruits)

Output:

{'apple', 'banana'}

Summary

  • add() adds a single item to a set.
  • update() adds multiple items to a set.
  • remove() deletes an item and raises an error if not found.
  • discard() deletes an item without raising an error.
  • pop() removes a random item.
  • clear() removes all items.
  • copy() creates a duplicate set.