Rishi

Posted on

# Learn Python: Sets

A set is another type of collection like `list` and `tuple`.

So what are sets?

• Sets are unordered – Items stored in a set aren’t kept in any particular order.
• Set items are unique – Duplicate items are not allowed.
• Sets are unindexed – You cannot access set items by referring to an index.
• Sets are changeable (mutable) – They can be changed in place, can grow and shrink on demand.

The values of a set are defined within curly braces `{` `}`.
A quick reminder:

• For `list`, we use square brackets `[` `]`.
• For `tuple`, we use brackets `(` `)`.
``````fruits = {'apple','orange'}
print(fruits);
``````

Sets don't maintain order. Every time we execute the code, the order of the values in the set changes.

Do note, in the example below we are adding `pineapple` multi times, but when we print the set, we only see `pineapple` once. This is because set does not allow duplicate.

``````fruits = {'apple','orange'}
print(fruits);
``````

## Benefits of sets

The key benefit of `sets` is that they make comparing values between two sets easier.

## Set Operations

Sets are commonly used for computing mathematical operations such as intersection, union, difference, and symmetric difference.

### Difference

``````basket_1 = {"Strawberry", "Cherry", "Apple", "Grapes"}

# Difference

``````

### Symmetric Difference

``````basket_1 = {"Strawberry", "Cherry", "Apple", "Grapes"}

# Symmetric Difference
``````

### Intersection

``````basket_1 = {"Strawberry", "Cherry", "Apple", "Grapes"}

# Intersection
``````

### Union

``````basket_1 = {"Strawberry", "Cherry", "Apple", "Grapes"}

# Union
``````

Waylon Walker

Sets are one of my favorite container types. You can do really powerful operations with very little effort, and they are wicked fast at it.

The one thing that I see your missing is the set operators like + * - | ^

Rishi

Waylon, Thanks!
Will definitely include that in another article about advance features of sets.

Much appreciated. Thanks.

Waylon Walker

As much as I like the tersness of the operators, and being able to quickly compare datasets ad-hoc, using the method names can be much more readable and less confusing. Good call to use those. I guess its worth a mention because you will run into them into the wild.

Ben Halpern

Love the use of replit here

Rishi

Javier,
Thank for your input, much appreciated.
I'm taking note, I'll definitely add that when I review it.

Again, thanks!