5 ways to create a set in Python

Updated: February 12, 2024 By: Guest Contributor Post a comment

Overview

This guide covers various ways to create sets in Python, complete with step-by-step implementations and practical examples. A set is an unordered collection of distinct elements which is highly useful for membership testing, removing duplicates, and mathematical operations like union, intersection, difference, and symmetric difference.

Using Set Literals

The most straightforward method to create a set. This approach is easiest for small, fixed-size sets with known elements.

  1. Begin by writing your elements enclosed in curly braces {}.
  2. Separate elements by commas.

Code Example:

my_set = {1, 2, 3, 4}
print(my_set)
# Output: {1, 2, 3, 4}

Notes: This method does not allow for the creation of an empty set; {} creates an empty dictionary instead. A very readable and concise method, but less dynamic.

Using the set() Constructor

Ideal for creating a new set from any iterable (like lists, tuples) or generating an empty set.

  1. To create an empty set, simply use set() with no arguments.
  2. To create a set from an iterable, pass the iterable as an argument to set().

Code Example:

empty_set = set()
print(empty_set)
# Output: set()

numbers = set([1, 2, 3, 4])
print(numbers)
# Output: {1, 2, 3, 4}

Notes: The set() constructor provides great flexibility and is ideal for dynamic set creation. However, it might introduce a slight overhead compared to literals due to function call overhead.

Comprehension Method

Python set comprehensions offer a concise way to dynamically create sets from iterables based on some condition.

  1. Start by enclosing the comprehension expression in curly braces {}.
  2. Use the syntax {expr for item in iterable} for a basic set comprehension, where expr defines the set’s elements based on the processing of item.

Code Example:

squares = {x**2 for x in range(5)}
print(squares)
# Output: {0, 1, 4, 9, 16}

Notes: Comprehensions are elegant and powerful, especially for applying transformations to each element. However, they might not be as readable to newcomers and may impact readability with complex expressions.

From a String

Creating a set directly from a string to get a collection of its unique characters. Just pass the string as an argument to the set() constructor.

Code Example:

chars = set("hello")
print(chars)
# Output: {'e', 'h', 'l', 'o'}

Notes: This method swiftly deduplicates characters in a string. Useful for character frequency and manipulation tasks.

Union Method for Merging Sets

Creating a new set by merging two existing sets without duplicate elements using the union operation. What to do is to utilize the | operator or the .union() method between two sets.

Code Example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
merged_set = set1 | set2
# Or
merged_set = set1.union(set2)
print(merged_set)
# Output: {1, 2, 3, 4, 5}

Notes: Union is an effective way to merge sets, especially when dealing with large datasets. Both methods produce the same result, but the | operator provides a more concise syntax.

Conclusion

In Python, sets are a versatile tool for handling unique collections. The choice of method to create a set greatly depends on the specific needs of your application, such as whether your data source is static or dynamic, or if your code prioritizes readability over performance. Understanding the various ways to construct sets will enhance your Python coding toolkit, allowing you to efficiently manage and manipulate collections of unique items.