Loading lesson...
Collections that guarantee uniqueness
Collections that guarantee uniqueness
Topics covered: What is a Set?, Creating Sets, Automatic Duplicate Removal, Removing Elements from Sets, What Can Be in a Set?
A set is an unordered collection of unique elements. These two properties define what makes a set different from other collection types like lists and tuples. Understanding both properties is essential for using sets correctly. The word "unordered" means that sets do not maintain any particular sequence for their elements. Unlike lists, where the first item you add stays first and the last item stays last, sets make no guarantees about element order. When you iterate over a set or print it, the
Python provides two main ways to create sets. You can use curly braces with elements inside, similar to how you write dictionary literals but without key-value pairs. Alternatively, you can use the set() constructor function, which can convert other iterables into sets. Each approach has specific use cases and limitations that you should understand. Using Curly Braces The most common and concise way to create a set with initial elements is using curly braces. Place your elements inside the brace
The automatic duplicate removal behavior of sets is one of their most powerful and useful features. Sets eliminate duplicates both during creation and when adding new elements. This happens silently, without errors or warnings. Understanding this behavior allows you to write cleaner, more concise code. Even though we specified "Alice" three times and "Bob" twice in the set literal, the resulting set contains each name exactly once. Python processes the elements in order, adding each one to the s
remove() vs discard() Both approaches handle missing elements gracefully. The if-check approach is explicit, while discard() handles it silently. Choose based on whether you want your code to acknowledge the absence or ignore it entirely. Try choosing different removal methods below to see how each one behaves when the element is missing from the set. The pop() Method The exact order in which elements are popped depends on Python's internal implementation and can vary between different runs or P
Not everything can be an element of a set. Set elements must be hashable, which generally means they must be immutable (unchangeable after creation). This requirement exists because sets use hashing to organize elements internally. If an element could change after being added, the set would not be able to find it anymore because its hash value would be different. Notice that the coordinate set shows only four points even though we specified five. The point (0, 0) was specified twice but only app