Ticker

6/recent/ticker-posts

Set Methods in Python

Set Methods in Python

Introduction
Sets in Python are unordered collections of unique elements. They are widely used for various operations such as intersection, union, and difference. In this documentation, we'll explore the different set methods available in Python with code examples and explanations.

1. add(element)

  • Adds a specified element to the set.
  • If the element is already present in the set, the set remains unchanged.
python
# Example:
fruits = {'apple', 'banana', 'orange'}
fruits.add('grape')
print(fruits) # Output: {'apple', 'banana', 'orange', 'grape'}

2. remove(element)

  • Removes the specified element from the set.
  • Raises a KeyError if the element is not found in the set.
python
# Example:
fruits = {'apple', 'banana', 'orange'}
fruits.remove('banana')
print(fruits) # Output: {'apple', 'orange'}

3. discard(element)

  • Removes the specified element from the set if it exists.
  • Does nothing if the element is not found in the set.
python
# Example:
fruits = {'apple', 'banana', 'orange'}
fruits.discard('grape')
print(fruits) # Output: {'apple', 'banana', 'orange'}

4. pop()

  • Removes and returns an arbitrary element from the set.
  • Raises a KeyError if the set is empty.
python
# Example:
fruits = {'apple', 'banana', 'orange'}
removed_fruit = fruits.pop()
print(removed_fruit) # Output: (an arbitrary element, e.g., 'apple')

5. clear()

  • Removes all elements from the set, making it empty.
python
# Example:
fruits = {'apple', 'banana', 'orange'}
fruits.clear()
print(fruits) # Output: set()

Conclusion
In this documentation, we covered various set methods in Python with their functionalities and provided code examples to illustrate their usage. Sets are powerful data structures that can efficiently handle unique collections and perform set operations. By understanding these set methods, you can effectively manipulate and work with sets in Python.

Post a Comment

0 Comments