Creating Sets with Braces or Constructor
๐ท๏ธ Tuples and Sets / Sets: Unique Collections
๐ง Context Introduction
Sets are one of Python's most useful data structures for engineers who need to work with unique collections of items. Unlike lists or tuples, sets automatically remove any duplicate values, making them perfect for tasks like filtering out repeated IP addresses, tracking unique error codes, or managing distinct configuration tags. In this section, we'll explore the two main ways to create sets: using curly braces and using the set() constructor.
โ๏ธ What is a Set?
- A set is an unordered collection of unique, immutable elements.
- Sets are defined using curly braces
{}or the built-in set() function. - Because sets are unordered, you cannot access items by index or position.
- Sets are mutable, meaning you can add or remove elements after creation.
๐ ๏ธ Creating Sets with Curly Braces
The most common and intuitive way to create a set is by placing comma-separated values inside curly braces.
Example:
- Code: server_ports = {80, 443, 22, 8080, 80}
- Result: The set will contain only {80, 443, 22, 8080} โ the duplicate 80 is automatically removed.
Key points: - Duplicate values are silently discarded. - Elements can be strings, numbers, or other immutable types. - You cannot use mutable types like lists or dictionaries as set elements.
Another example:
- Code: error_codes = {"404", "500", "403", "404", "200"}
- Result: {"404", "500", "403", "200"} โ duplicates are eliminated.
๐งฐ Creating Sets with the set() Constructor
The set() constructor allows you to create a set from any iterable object, such as a list, tuple, or string. This is especially useful when you already have data in another format and want to convert it into a unique collection.
Example from a list:
- Code: ip_list = ["192.168.1.1", "10.0.0.1", "192.168.1.1", "172.16.0.1"]
- Code: unique_ips = set(ip_list)
- Result: {"192.168.1.1", "10.0.0.1", "172.16.0.1"}
Example from a string:
- Code: hostname = "database01"
- Code: unique_chars = set(hostname)
- Result: {"d", "a", "t", "b", "s", "e", "0", "1"} โ each character appears only once.
Example from a tuple:
- Code: config_versions = (2.1, 2.3, 2.1, 2.4, 2.3)
- Code: unique_versions = set(config_versions)
- Result: {2.1, 2.3, 2.4}
๐ Comparison: Braces vs. Constructor
| Feature | Curly Braces {} |
set() Constructor |
|---|---|---|
| Syntax | Directly list values inside {} |
Pass an iterable to set() |
| Best for | Creating a set from scratch with known values | Converting existing data (list, tuple, string) into a set |
| Empty set | Not possible โ {} creates an empty dictionary |
set() creates an empty set |
| Readability | Very clean for small, fixed collections | Clear when transforming data from another structure |
๐ต๏ธ Important Gotchas
- Empty set trap: Using empty curly braces
{}creates an empty dictionary, not a set. Always useset()for an empty set. - Unordered nature: The order of elements in a set is not guaranteed. If you run the same code twice, the output order may differ.
- Immutable elements only: You can store numbers, strings, and tuples in a set, but not lists or dictionaries.
Example of the empty set trap:
- Code: empty_container = {}
- Type: This is a dictionary, not a set.
- Correct approach: empty_set = set()
๐งช Practical Example for Engineers
Imagine you are collecting status codes from multiple server logs and want to see all unique codes that appeared.
Using braces:
- Code: status_codes = {200, 404, 500, 200, 301, 404}
- Result: {200, 301, 404, 500} โ you now have a clean set of all unique status codes.
Using constructor from a list:
- Code: log_codes = [200, 404, 500, 200, 301, 404, 500, 200]
- Code: unique_codes = set(log_codes)
- Result: {200, 301, 404, 500} โ same result, but built from existing data.
โ Summary
- Use curly braces
{}to create a set directly with known values. - Use the set() constructor to convert existing lists, tuples, or strings into a set.
- Sets automatically remove duplicates, making them ideal for deduplication tasks.
- Remember:
{}is a dictionary, not a set โ useset()for empty sets. - Sets are unordered and only accept immutable elements.
Mastering set creation is a small but powerful step toward writing cleaner, more efficient Python code for managing unique collections in your daily engineering work.
Sets store unique unordered items and can be created using curly braces {} or the set() constructor.
๐ง Example 1: Creating a set with curly braces
This shows the most basic way to create a set using curly braces.
colors = {"red", "blue", "green"}
print(colors)
๐ค Output: {'blue', 'green', 'red'}
๐ง Example 2: Creating an empty set with the constructor
This shows that {} creates an empty dictionary, so you must use set() for an empty set.
empty_set = set()
print(empty_set)
print(type(empty_set))
๐ค Output: set()
๐ง Example 3: Creating a set from a list (removes duplicates)
This shows how the set() constructor automatically removes duplicate values.
numbers = [1, 2, 2, 3, 3, 3]
unique_numbers = set(numbers)
print(unique_numbers)
๐ค Output: {1, 2, 3}
๐ง Example 4: Creating a set from a string (splits into characters)
This shows how the constructor breaks a string into individual characters and keeps only unique ones.
word = "engineer"
unique_letters = set(word)
print(unique_letters)
๐ค Output: {'e', 'g', 'i', 'n', 'r'}
๐ง Example 5: Creating a set with mixed data types
This shows that sets can hold different data types together.
mixed_set = {42, "hello", 3.14, True}
print(mixed_set)
๐ค Output: {True, 3.14, 42, 'hello'}
Comparison Table: Braces vs Constructor
| Feature | Curly Braces {} |
Constructor set() |
|---|---|---|
| Basic usage | {1, 2, 3} |
set([1, 2, 3]) |
| Empty set | โ Creates empty dict | โ
set() works |
| From iterable | โ Not possible | โ
set("abc") |
| Duplicate removal | โ Automatic | โ Automatic |
| Readability | Best for literals | Best for conversions |
๐ง Context Introduction
Sets are one of Python's most useful data structures for engineers who need to work with unique collections of items. Unlike lists or tuples, sets automatically remove any duplicate values, making them perfect for tasks like filtering out repeated IP addresses, tracking unique error codes, or managing distinct configuration tags. In this section, we'll explore the two main ways to create sets: using curly braces and using the set() constructor.
โ๏ธ What is a Set?
- A set is an unordered collection of unique, immutable elements.
- Sets are defined using curly braces
{}or the built-in set() function. - Because sets are unordered, you cannot access items by index or position.
- Sets are mutable, meaning you can add or remove elements after creation.
๐ ๏ธ Creating Sets with Curly Braces
The most common and intuitive way to create a set is by placing comma-separated values inside curly braces.
Example:
- Code: server_ports = {80, 443, 22, 8080, 80}
- Result: The set will contain only {80, 443, 22, 8080} โ the duplicate 80 is automatically removed.
Key points: - Duplicate values are silently discarded. - Elements can be strings, numbers, or other immutable types. - You cannot use mutable types like lists or dictionaries as set elements.
Another example:
- Code: error_codes = {"404", "500", "403", "404", "200"}
- Result: {"404", "500", "403", "200"} โ duplicates are eliminated.
๐งฐ Creating Sets with the set() Constructor
The set() constructor allows you to create a set from any iterable object, such as a list, tuple, or string. This is especially useful when you already have data in another format and want to convert it into a unique collection.
Example from a list:
- Code: ip_list = ["192.168.1.1", "10.0.0.1", "192.168.1.1", "172.16.0.1"]
- Code: unique_ips = set(ip_list)
- Result: {"192.168.1.1", "10.0.0.1", "172.16.0.1"}
Example from a string:
- Code: hostname = "database01"
- Code: unique_chars = set(hostname)
- Result: {"d", "a", "t", "b", "s", "e", "0", "1"} โ each character appears only once.
Example from a tuple:
- Code: config_versions = (2.1, 2.3, 2.1, 2.4, 2.3)
- Code: unique_versions = set(config_versions)
- Result: {2.1, 2.3, 2.4}
๐ Comparison: Braces vs. Constructor
| Feature | Curly Braces {} |
set() Constructor |
|---|---|---|
| Syntax | Directly list values inside {} |
Pass an iterable to set() |
| Best for | Creating a set from scratch with known values | Converting existing data (list, tuple, string) into a set |
| Empty set | Not possible โ {} creates an empty dictionary |
set() creates an empty set |
| Readability | Very clean for small, fixed collections | Clear when transforming data from another structure |
๐ต๏ธ Important Gotchas
- Empty set trap: Using empty curly braces
{}creates an empty dictionary, not a set. Always useset()for an empty set. - Unordered nature: The order of elements in a set is not guaranteed. If you run the same code twice, the output order may differ.
- Immutable elements only: You can store numbers, strings, and tuples in a set, but not lists or dictionaries.
Example of the empty set trap:
- Code: empty_container = {}
- Type: This is a dictionary, not a set.
- Correct approach: empty_set = set()
๐งช Practical Example for Engineers
Imagine you are collecting status codes from multiple server logs and want to see all unique codes that appeared.
Using braces:
- Code: status_codes = {200, 404, 500, 200, 301, 404}
- Result: {200, 301, 404, 500} โ you now have a clean set of all unique status codes.
Using constructor from a list:
- Code: log_codes = [200, 404, 500, 200, 301, 404, 500, 200]
- Code: unique_codes = set(log_codes)
- Result: {200, 301, 404, 500} โ same result, but built from existing data.
โ Summary
- Use curly braces
{}to create a set directly with known values. - Use the set() constructor to convert existing lists, tuples, or strings into a set.
- Sets automatically remove duplicates, making them ideal for deduplication tasks.
- Remember:
{}is a dictionary, not a set โ useset()for empty sets. - Sets are unordered and only accept immutable elements.
Mastering set creation is a small but powerful step toward writing cleaner, more efficient Python code for managing unique collections in your daily engineering work.
Interactive Views
You are currently in ๐ All-in-One mode. Use the tabs at the top to switch to ๐ Theory Only or ๐ป Code Only views.
Sets store unique unordered items and can be created using curly braces {} or the set() constructor.
๐ง Example 1: Creating a set with curly braces
This shows the most basic way to create a set using curly braces.
colors = {"red", "blue", "green"}
print(colors)
๐ค Output: {'blue', 'green', 'red'}
๐ง Example 2: Creating an empty set with the constructor
This shows that {} creates an empty dictionary, so you must use set() for an empty set.
empty_set = set()
print(empty_set)
print(type(empty_set))
๐ค Output: set()
๐ง Example 3: Creating a set from a list (removes duplicates)
This shows how the set() constructor automatically removes duplicate values.
numbers = [1, 2, 2, 3, 3, 3]
unique_numbers = set(numbers)
print(unique_numbers)
๐ค Output: {1, 2, 3}
๐ง Example 4: Creating a set from a string (splits into characters)
This shows how the constructor breaks a string into individual characters and keeps only unique ones.
word = "engineer"
unique_letters = set(word)
print(unique_letters)
๐ค Output: {'e', 'g', 'i', 'n', 'r'}
๐ง Example 5: Creating a set with mixed data types
This shows that sets can hold different data types together.
mixed_set = {42, "hello", 3.14, True}
print(mixed_set)
๐ค Output: {True, 3.14, 42, 'hello'}
Comparison Table: Braces vs Constructor
| Feature | Curly Braces {} |
Constructor set() |
|---|---|---|
| Basic usage | {1, 2, 3} |
set([1, 2, 3]) |
| Empty set | โ Creates empty dict | โ
set() works |
| From iterable | โ Not possible | โ
set("abc") |
| Duplicate removal | โ Automatic | โ Automatic |
| Readability | Best for literals | Best for conversions |