Create Unique Unordered Collections in Python with Set

Will Button
InstructorWill Button
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

A set is an unordered collection with no duplicate items in Python. In this lesson, you will learn how to create them, and perform basic operations to determine members in the set and compare the values from different sets.

I can create a set in Python by giving it the variable name, starting with a curly bracket and then starting to add my set items to it. I can add a list of animals here including monkey, bear, dog, and then I'm going to add monkey again. We'll add a cat to it, we'll add another bear, and then we'll add a gorilla. Now if I print this out for you, you can see that it eliminated the duplicates, so that's the key to a set. It doesn't allow duplicate values which makes it good for membership testing.

For membership testing, in order to see which values are in it we can say monkey in animals, it will return true. This works very quick, even for large sets. If we ask for something that's not in there, it'll return false. Then here's the tricky part. If you want to create an empty set, whenever I created the one for animals above I used the curly braces. If I want to create an empty set, I have to use the word set with parentheses after it.

To add something to it, we have an add method, and I can add a shark to it. I can add a guppy to it, and I can add a whale to it. Then when we take a look at it, it prints out. Then I can remove items using the remove method, now I'll remove whale because it's not actually a fish. Sets also have a union method which allows you to merge two different sets together. I can merge fish with animals and it returns a new set that contains the de-duplicated values from both of those lists.

egghead
egghead
~ 8 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today