Level 1
0 / 100 XP

Python Sets

In Python, a set is a data structure that stores an unordered collection of unique items. Unlike a list or a tuple, a set does not allow duplicate items, and the items in a set are not ordered. In Python, sets are represented by curly braces {} and the items in a set are separated by commas.

Creating a Set

To create a set in Python, use curly braces {} and separate the items in the set with commas. Here are some examples of creating sets in Python:

Text
# Create an empty set my_set = set() # Create a set of numbers numbers = {1, 2, 3, 4, 5} # Create a set of strings colors = {"red", "green", "blue"} # Create a set of mixed data types mixed = {1, "two", 3.0, (4, 5)}

As you can see, a set can store items of any data type, but it does not allow duplicate items.

Accessing and Modifying Set Items

In Python, you cannot access the items in a set using indexing, because sets are unordered collections of items. Instead, you can use the in keyword to check if an item is in a set, and you can use the add() and remove() methods to add or remove items from a set. Here are some examples of accessing and modifying set items in Python:

Python
# Check if an item is in a set print(1 in numbers) # Output: True # Add an item to a set numbers.add(6) print(numbers) # Output: {1, 2, 3, 4, 5, 6} # Remove an item from a set numbers.remove(4) print(numbers) # Output: {1, 2, 3, 5, 6}

As you can see, you can use the in keyword and the add() and remove() methods to access and modify the items in a set.

Common Set Methods

In Python, sets have a few built-in methods that allow you to manipulate the items in a set. Here are some common set methods that you might find useful:

  • add(): adds an item to a set
  • remove(): removes an item from a set
  • union(): returns the un…