From the course: Programming Foundations: Data Structures

What is a set?

- Let's talk about another way we can structure our data with the set. Like with the raised from before, a set is an abstract data type. It's an idea that can be implemented in many different ways. In the simplest of terms, a set is a collection of unique items. The order of these items doesn't matter, but there are no duplicate elements. Now, why would we want to keep track of data in this way? Well, sets are a way of grouping things with a common property. For example, you might create a set that represents different types of shirts you can wear or a set of colors. You could also create a set that represents the names of the fingers we have. Think pinky, ring, middle finger, and index. With sets, we don't care about the order of the elements and often we don't even want to retrieve a piece of data. That's why we don't have an index or a key or anything to look up a specific value. With sets, we are usually testing if a piece of data is a member in the set we care about if the set contains a given number or character or string, and in the implementation, the structure will be optimized for this specific operation. So how are sets implemented? As we've seen before, certain data structures are great for lookup or search and others are not. In a list, we might have to do a linear search of the entire structure. Behind the scenes, sets are actually using the same idea as dictionaries. However, instead of using a key to store a separate value object, the key is the value. We don't have two pieces of information. We are just adding one. With sets, we mostly care about membership In checking to see if an object is in the set, We already need to have the object itself, which is why we almost never use sets for retrieval of data.

Contents