zaro

How Do You Store a Set in Python?

Published in Python Data Structures 3 mins read

You store a set in Python by defining it using curly braces {} or the set() function. These are the primary ways to create and initialize set objects, which are then stored in a variable.

Python sets are powerful, built-in data structures. As noted in the reference, they are unordered collections of unique elements. This means:

  • Unordered: The elements do not have a defined order, and you cannot access them using indexes or slices.
  • Unique: Duplicate elements are automatically removed when a set is created.

Sets are particularly useful for storing distinct items and performing mathematical set operations like union, intersection, and difference, as highlighted in the reference.

Methods to Store a Set

There are two main ways to create and store a set in Python:

1. Using Curly Braces {}

This is the most common way to define a non-empty set with initial values.

# Storing a set using curly braces
my_fruits = {"apple", "banana", "cherry"}
print(my_fruits)
# Output may vary in order: {'cherry', 'apple', 'banana'}

# Sets automatically handle duplicates
my_numbers = {1, 2, 2, 3, 4, 4, 5}
print(my_numbers)
# Output: {1, 2, 3, 4, 5}
  • Note: You cannot create an empty set using just {} because {} is used to create an empty dictionary.

2. Using the set() Function

The set() function is versatile. It can be used to create an empty set or to convert an iterable (like a list, tuple, or string) into a set.

# Storing an empty set using set()
empty_set = set()
print(empty_set)
# Output: set()

# Storing a set by converting a list
my_list = [10, 20, 30, 20, 40]
set_from_list = set(my_list)
print(set_from_list)
# Output: {40, 10, 20, 30} (order varies)

# Storing a set by converting a string (creates a set of characters)
set_from_string = set("hello")
print(set_from_string)
# Output: {'o', 'l', 'e', 'h'} (order varies)

Comparing Set Creation Methods

Here's a quick look at the different ways to initialize sets:

Method Purpose Example Resulting Type
{element1, ...} Create a non-empty set my_set = {1, 'a', 3} set
set() Create an empty set empty_set = set() set
set(iterable) Convert an iterable to a set set_from_list = set([1, 2, 1]) set

Practical Uses

Because sets store unique items and support fast membership testing and set operations, they are ideal for tasks such as:

  • Removing Duplicates: Easily get a collection of unique items from a list or other iterable.
  • Membership Testing: Quickly check if an item is present in the set (item in my_set).
  • Set Operations: Perform union, intersection, difference, and symmetric difference between sets efficiently.

In summary, storing a set in Python involves creating a set object using either the {} syntax for non-empty sets or the set() function, and then assigning it to a variable.