🔨 Creating Sets
Creating sets in Python is easy and flexible. You can make sets using curly braces {}
, the set()
function, or set comprehensions. Each method has its own advantages depending on your situation and data source.
Let's explore all the ways to create sets:
# Basic set creation
numbers = {1, 2, 3, 4, 5}
colors = {"red", "green", "blue"}
mixed = {1, "hello", 3.14}
print(f"Numbers: {numbers}")
print(f"Colors: {colors}")
print(f"Mixed types: {mixed}")
🎯 Basic Set Creation Syntax
The most common way to create sets is using curly braces with comma-separated values.
Using Curly Braces
Creating sets directly with curly brace syntax.
# Creating sets with curly braces
fruits = {"apple", "banana", "orange"}
numbers = {10, 20, 30, 40}
grades = {"A", "B", "C", "D", "F"}
print(f"Fruits: {fruits}")
print(f"Numbers: {numbers}")
print(f"Grades: {grades}")
Automatic Duplicate Removal
Sets automatically remove duplicate values during creation.
# Duplicates are automatically removed
numbers_with_duplicates = {1, 2, 2, 3, 3, 3, 4}
print(f"Original: {1, 2, 2, 3, 3, 3, 4}")
print(f"Set result: {numbers_with_duplicates}")
# Useful for cleaning data
survey_responses = {"yes", "no", "yes", "maybe", "yes", "no"}
unique_responses = survey_responses
print(f"Unique survey responses: {unique_responses}")
Mixed Data Types
Sets can contain different types of immutable objects.
# Mixed data types in sets
mixed_set = {42, "hello", 3.14, True}
coordinates = {(0, 0), (1, 1), (2, 2)}
identifiers = {1001, "USER123", (2024, 1, 15)}
print(f"Mixed set: {mixed_set}")
print(f"Coordinate set: {coordinates}")
print(f"ID set: {identifiers}")
⚡ Using the set() Function
The set()
function is more flexible and can create sets from other data types.
Creating Empty Sets
The correct way to create an empty set.
# Creating empty sets
empty_set = set() # Correct way
print(f"Empty set: {empty_set}")
print(f"Type: {type(empty_set)}")
# This creates a dictionary, not a set!
empty_dict = {}
print(f"Empty dict: {empty_dict}")
print(f"Type: {type(empty_dict)}")
From Lists and Tuples
Converting lists and tuples to sets.
# From lists
number_list = [1, 2, 3, 4, 5, 1, 2] # Has duplicates
number_set = set(number_list)
print(f"From list: {number_set}")
# From tuples
color_tuple = ("red", "green", "blue", "red")
color_set = set(color_tuple)
print(f"From tuple: {color_set}")
# From ranges
range_set = set(range(1, 6))
print(f"From range: {range_set}")
From Strings
Creating sets from string characters.
# Sets from strings
word = "hello"
letter_set = set(word)
print(f"Letters in '{word}': {letter_set}")
# Remove duplicate letters
text = "programming"
unique_letters = set(text)
print(f"Unique letters in '{text}': {unique_letters}")
print(f"Number of unique letters: {len(unique_letters)}")
🚀 Set Comprehensions
Set comprehensions create sets using a compact syntax similar to list comprehensions.
Basic Set Comprehensions
Creating sets using comprehension syntax.
# Basic set comprehensions
squares = {x**2 for x in range(6)}
print(f"Squares: {squares}")
# From existing data
numbers = [1, 2, 3, 4, 5]
doubled = {x * 2 for x in numbers}
print(f"Doubled: {doubled}")
# String transformations
words = ["apple", "BANANA", "Orange"]
lowercase = {word.lower() for word in words}
print(f"Lowercase: {lowercase}")
Conditional Set Comprehensions
Adding conditions to filter elements during creation.
# Set comprehensions with conditions
numbers = range(1, 11)
# Even numbers only
evens = {x for x in numbers if x % 2 == 0}
print(f"Even numbers: {evens}")
# Numbers divisible by 3
divisible_by_3 = {x for x in numbers if x % 3 == 0}
print(f"Divisible by 3: {divisible_by_3}")
# Squared odd numbers
odd_squares = {x**2 for x in numbers if x % 2 == 1}
print(f"Squared odd numbers: {odd_squares}")
Complex Transformations
Using comprehensions for more complex data processing.
# Complex transformations
words = ["python", "java", "javascript", "go", "rust"]
# Words longer than 4 characters, uppercase
long_words = {word.upper() for word in words if len(word) > 4}
print(f"Long words (uppercase): {long_words}")
# First letter of each word
first_letters = {word[0] for word in words}
print(f"First letters: {first_letters}")
# Word lengths
word_lengths = {len(word) for word in words}
print(f"Word lengths: {word_lengths}")
🌟 Creating Sets from Different Sources
Sets can be created from various data sources depending on your needs.
From User Input
Creating sets from user-provided data.
# Simulate user input (in real code, use input())
user_input = "apple,banana,apple,orange,banana"
print(f"User input: {user_input}")
# Split and create set
fruit_list = user_input.split(",")
fruit_set = set(fruit_list)
print(f"Unique fruits: {fruit_set}")
# Clean whitespace
messy_input = " red , green , blue , red "
cleaned = {item.strip() for item in messy_input.split(",")}
print(f"Cleaned set: {cleaned}")
From Nested Data
Creating sets from complex data structures.
# From nested lists
student_groups = [
["Alice", "Bob", "Carol"],
["Bob", "David", "Eve"],
["Carol", "Frank", "Alice"]
]
# Get all unique students
all_students = set()
for group in student_groups:
all_students.update(group)
print(f"All students: {all_students}")
# Using comprehension (flattened)
students_flat = {student for group in student_groups for student in group}
print(f"Students (comprehension): {students_flat}")
# Extract email domains
emails = [
"alice@gmail.com",
"bob@yahoo.com",
"carol@gmail.com",
"david@yahoo.com"
]
domains = {email.split("@")[1] for email in emails}
print(f"Email domains: {domains}")
💡 Set Creation Best Practices
Following best practices ensures efficient and maintainable set creation.
Efficient Set Creation
Choosing the most efficient method for different scenarios.
# Efficient methods for different cases
# Small known sets - use literal syntax
primary_colors = {"red", "green", "blue"}
# Remove duplicates - use set() function
data_with_dupes = [1, 2, 2, 3, 3, 3, 4, 4]
unique_data = set(data_with_dupes)
# Transform data - use comprehension
numbers = range(10)
even_squares = {x**2 for x in numbers if x % 2 == 0}
print(f"Primary colors: {primary_colors}")
print(f"Unique data: {unique_data}")
print(f"Even squares: {even_squares}")
Error-Free Set Creation
Avoiding common mistakes when creating sets.
# Common mistakes and solutions
# Mistake: Using {} for empty set
# empty_set = {} # This creates a dict!
correct_empty_set = set() # Correct
# Mistake: Trying to add mutable objects
# invalid_set = {[1, 2], [3, 4]} # Error!
valid_set = {(1, 2), (3, 4)} # Use tuples instead
# Mistake: Expecting order preservation
unordered = {3, 1, 4, 1, 5} # Order not guaranteed
print(f"Empty set: {correct_empty_set}")
print(f"Valid set: {valid_set}")
print(f"Unordered set: {unordered}")
📚 Set Creation Reference
Common set creation patterns and their use cases:
Method | Syntax | Use Case | Example |
---|---|---|---|
Literal | {1, 2, 3} | Small known sets | colors = {"red", "green", "blue"} |
Empty | set() | Initialize empty | unique_items = set() |
From List | set(list) | Remove duplicates | set([1, 2, 2, 3]) |
From String | set(string) | Unique characters | set("hello") |
Comprehension | {expr for x in iter} | Transform data | {x*2 for x in range(5)} |
Conditional | {expr for x in iter if cond} | Filter + transform | {x for x in range(10) if x % 2 == 0} |
Choose the method that best fits your data source and requirements.
Learn more about reading set data and adding to sets to continue working with sets.
Hands-on Exercise
Create a set of unique numbers from a list that contains duplicates. Then add a new number to the set.
numbers = [1, 2, 3, 2, 1, 4, 3, 5]
# TODO: Create a set from the numbers list
unique_numbers = # TODO: Your set here
# TODO: Add the number 6 to the set
# TODO: Your add operation here
print(f"Original list: {numbers}")
print(f"Unique numbers: {unique_numbers}")
Solution and Explanation 💡
Click to see the complete solution
numbers = [1, 2, 3, 2, 1, 4, 3, 5]
# Create a set from the numbers list
unique_numbers = set(numbers)
# Add the number 6 to the set
unique_numbers.add(6)
print(f"Original list: {numbers}")
print(f"Unique numbers: {unique_numbers}")
Key Learning Points:
- 📌 set() function: Use
set(list)
to create a set from a list and remove duplicates - 📌 Automatic deduplication: Sets automatically remove duplicate values
- 📌 add() method: Use
set.add(item)
to add a single item to a set - 📌 Unordered collection: Sets don't maintain the original order of elements
Test Your Knowledge
Test what you've learned about creating sets in Python:
What's Next?
Now that you can create sets, you're ready to learn how to access and examine set data. Understanding how to read set information is essential for working with set contents effectively.
Ready to continue? Check out our lesson on Reading Set Data.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.