🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Python Sets

Introduction to Sets in Python

Introduction to Sets in Python

In Python, a set is an unordered collection of unique elements. Sets are defined by enclosing elements in curly braces {} or by using the set() constructor. Here are some key features and operations related to Python sets:

1. Creating Sets:

# Using curly braces
fruits = {'apple', 'banana', 'orange'}

# Using set() constructor
numbers = set([1, 2, 3, 4, 5])

2. Set Operations:

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

union_set = set1 | set2          # Union
intersection_set = set1 & set2    # Intersection
difference_set = set1 - set2      # Difference
symmetric_difference_set = set1 ^ set2  # Symmetric Difference

3. Adding and Removing Elements:

numbers = {1, 2, 3}

numbers.add(4)         # Add element
numbers.remove(2)      # Remove element (raises an error if not present)
numbers.discard(3)     # Remove element (ignores if not present)

4. Set Methods:

numbers = {1, 2, 3, 4}

numbers.add(5)
numbers.remove(3)
numbers.clear()

5. Checking Membership:

fruits = {'apple', 'banana', 'orange'}
has_apple = 'apple' in fruits      # True
has_mango = 'mango' not in fruits  # True

6. Set Comprehension:

squares_set = {x**2 for x in range(5)}

7. Frozen Sets:

frozen_numbers = frozenset([1, 2, 3, 4, 5])

Sets are useful for tasks that involve testing membership, eliminating duplicate entries, and performing set operations. However, sets do not maintain the order of elements. If order is important, you may want to use a different collection type, such as a list or tuple.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.