A set in Python is a collection that holds unique values with no particular order

A set is one of Python's built-in data types, similar to a list or dictionary. The key difference is that a set automatically removes duplicates and does not keep items in any specific order. If you add the same value twice, the set keeps only one copy. This makes sets useful when you need to track which items exist without caring about how many times they appear or what sequence they came in.

You create a set by putting values inside curly braces, separated by commas. Python then stores those values in a way that makes it fast to check whether a specific item is in the set. You can add items, remove items, and compare sets to find what they have in common or what makes them different.

Key Takeaways

  • Create a set by typing curly braces with comma-separated values: my_set = {1, 2, 3} or use the set() function for an empty set.
  • Sets automatically discard duplicate values, so adding the same item twice results in only one copy in the set.
  • Use add() to insert a single item and remove() or discard() to delete items from a set.
  • Compare sets with methods like union(), intersection(), and difference() to find shared values or unique values between two sets.

Creating a set with curly braces or the set() function

The simplest way to create a set is to type values inside curly braces. For example, colors = {"red", "blue", "green"} creates a set with three color names. You can include integers, strings, or other immutable types. Python automatically recognizes this as a set and stores it accordingly.

If you want to create an empty set, you cannot use empty curly braces {} because Python interprets that as an empty dictionary instead. Use the set() function: empty_set = set(). You can also convert other collections into a set by passing them to set(). For instance, set([1, 2, 2, 3]) becomes {1, 2, 3} because the duplicate 2 is removed.

How duplicates are automatically removed

When you create a set or add items to one, Python silently discards any duplicates. If you type numbers = {5, 10, 5, 15}, the resulting set contains only {5, 10, 15}. This happens because sets are designed to hold unique values only—that is their defining feature.

This behavior is useful when you have a list with repeated values and need to know which distinct items appear in it. Instead of writing code to loop through and check for duplicates, you can convert the list to a set in one line. For example, unique_items = set([1, 2, 2, 3, 3, 3]) gives you {1, 2, 3} when ready.

Adding and removing items from a set

To add a single item to an existing set, use the add() method. Type my_set.add(4) to insert the value 4. If 4 is already in the set, nothing happens—no duplicate is created. To add multiple items at once, use update() with a list or another set: my_set.update([5, 6, 7]).

To remove an item, you have two options. The remove() method deletes a value and raises an error if that value does not exist in the set. The discard() method also deletes a value but does nothing if it is not there. Use discard() when you are not sure whether the item exists. For example, my_set.discard(3) removes 3 if it is present, and causes no error if it is not.

Comparing sets to find shared and unique values

Sets have built-in methods that let you compare two sets and find relationships between them. The intersection() method returns a new set containing only the values that appear in both sets. If set_a = {1, 2, 3} and set_b = {2, 3, 4}, then set_a.intersection(set_b) returns {2, 3}.

The union() method combines two sets and returns all unique values from both. Using the same example, set_a.union(set_b) returns {1, 2, 3, 4}. The difference() method shows what is in the first set but not in the second. So set_a.difference(set_b) returns {1} because 1 appears in set_a but not in set_b.

When to use sets instead of lists or dictionaries

Use a set when you care about whether a value exists, not how many times it appears or what order it came in. Checking whether an item is in a set is very fast, even with thousands of values. If you write if 42 in my_set, Python can answer almost when ready. With a list, Python has to look through every item one by one, which slows down as the list grows.

Sets are also the right choice when you need to remove duplicates from a collection or find what values two collections have in common. If you are building a program that tracks user IDs, email addresses, or product codes, a set prevents accidental duplicates and makes comparisons straightforward. Use a list when order matters or when you need to store the same value multiple times. Use a dictionary when you need to pair each value with information about it.

Common mistakes when working with sets

One frequent mistake is trying to create an empty set with {}. This creates a dictionary, not a set. Always use set() for an empty set. Another mistake is trying to add a list or dictionary to a set. Sets can only hold immutable types like integers, strings, and tuples. If you try my_set.add([1, 2, 3]), Python raises an error because lists can be changed.

A third mistake is assuming sets maintain order. They do not. If you add items in the order 1, 2, 3, they might print in a different order. If order matters for your program, use a list instead. Finally, remember that remove() raises an error if the item is not in the set, while discard() does not. Choose the right one based on whether you want Python to alert you if the item is missing.

Frequently Asked Questions

Can I add a list or dictionary to a set?

No. Sets can only hold immutable types like integers, strings, floats, and tuples. Lists and dictionaries can be modified, so Python does not allow them in sets. If you need to store a collection inside a set, convert the list to a tuple first: my_set.add(tuple([1, 2, 3])).

What is the difference between remove() and discard()?

Both delete an item from a set, but remove() raises an error if the item does not exist, while discard() does nothing. Use remove() when you expect the item to be there and want to know if something went wrong. Use discard() when you are not sure whether the item exists.

Why does my set print in a different order each time?

Sets do not maintain order. Python stores set items in a way that makes lookups fast, not in the order you added them. If you need items in a specific order, use a list instead. If you need both uniqueness and order, you can sort a set into a list: sorted_list = sorted(my_set).

How do I check if a value is in a set?

Use the in operator: if 5 in my_set:. This is very fast even with large sets. You can also use not in to check if a value is absent: if 5 not in my_set:.