How to Create a Set in Python: Syntax and Examples
In Python, you create a set using the
set() function or by enclosing items in curly braces {}. Sets store unique items without order, so duplicates are removed automatically.Syntax
You can create a set in two main ways:
- Using curly braces: Enclose comma-separated values inside
{}. Example:{1, 2, 3} - Using the
set()function: Pass an iterable like a list or string toset(). Example:set([1, 2, 3])
Note: To create an empty set, use set() because {} creates an empty dictionary.
python
my_set = {1, 2, 3}
my_other_set = set([4, 5, 6])
empty_set = set()Example
This example shows how to create sets using both curly braces and the set() function. It also demonstrates that duplicates are removed automatically.
python
fruits = {'apple', 'banana', 'apple', 'orange'}
print(fruits) # Duplicates removed
numbers = set([1, 2, 2, 3, 4])
print(numbers) # Duplicates removed
empty = set()
print(empty) # Empty setOutput
{'banana', 'orange', 'apple'}
{1, 2, 3, 4}
set()
Common Pitfalls
One common mistake is trying to create an empty set using {}, but this actually creates an empty dictionary. Always use set() for an empty set.
Another pitfall is expecting sets to keep the order of items. Sets do not keep order, so the output order may differ from the input.
python
empty_wrong = {}
print(type(empty_wrong)) # Outputs: <class 'dict'>
empty_right = set()
print(type(empty_right)) # Outputs: <class 'set'>Output
<class 'dict'>
<class 'set'>
Quick Reference
| Action | Syntax | Description |
|---|---|---|
| Create set with items | {1, 2, 3} | Set with unique items |
| Create set from list | set([1, 2, 3]) | Convert list to set |
| Create empty set | set() | Empty set |
| Create empty dictionary | {} | Empty dictionary, not a set |
Key Takeaways
Use curly braces {} or set() to create sets in Python.
Always use set() to create an empty set, not {}.
Sets automatically remove duplicate items and do not keep order.
Passing a list or other iterable to set() converts it to a set.
Remember that {} creates an empty dictionary, not a set.