Introduction to Python Sets

Welcome, Pythonist! Our focus today is Python sets, which are mutable containers of unique items. With your newfound skills in managing sets, you'll be able to handle any collection of non-duplicated items with ease. Ready? Let's begin!

Sets in Python are user-defined collections of unique items. They're unordered yet mutable. Imagine you've got apples, bananas, and oranges in a basket, and you want only unique fruits. That's where sets come into play, eliminating duplicates and leaving only the unique items behind.

Creating Sets in Python

Creating Python sets is easy. Just enclose your items in {} or use the set() function. Let's try it:

# Creating a set using curly braces
fruit_set = {'apple', 'banana', 'cherry', 'apple'}
print(fruit_set)  # Outputs: {'cherry', 'banana', 'apple'}

# Using set() function
list_to_set = set(['apple', 'banana', 'cherry', 'apple'])
print(list_to_set)  # Outputs: {'cherry', 'banana', 'apple'}

Even though we added 'apple' twice, it appears only once because sets automatically remove duplicates.

Accessing Elements in Sets

Sets don't support access through indexing. However, Python does allow keyword searches with in. Here's how:

fruit_set = {'apple', 'banana', 'cherry'}

print('banana' in fruit_set)  # Outputs: True
print('kiwi' in fruit_set)    # Outputs: False
Modifying Sets in Python

As mutable entities, sets allow us to add or delete items. Add items using the add() method and remove items with the remove() method. For example:

fruit_set = {'apple', 'banana', 'cherry'}
fruit_set.add('orange')
print(fruit_set)  # Outputs: {'cherry', 'orange', 'banana', 'apple'}

fruit_set.remove('apple')
print(fruit_set)  # Outputs: {'cherry', 'orange', 'banana'}
Python Set Operations

Python supports several set operations:

  • Union (|) - unites elements from two sets into one big set, resolving duplicate occurrences.
  • Intersection (&) - creates a new set containing only elements that exist in both sets.
  • Difference (-) - Elements that are present only in the first set but not in the second.

Here's an example:

setA = {1, 2, 3, 4, 5}
setB = {4, 5, 6, 7, 8}

print(setA | setB)  # Uniting two sets; Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(setA & setB)  # Intersecting two sets; Output: {4, 5}
print(setA - setB)  # Sets difference; Output: {1, 2, 3}
print(setB - setA)  # Sets difference; Output: {6, 7, 8}

These operations, which resemble those of mathematical sets, help remove common items and find unique items across two sets.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal