Python Sets: How to Store Unique Items Fast
Photo: Wikimedia Commons Python sets are handy tools for keeping only unique items in a single list. You can drop duplicate values fast without writing long loops. A set is an unordered collection of items where every item must be unique. If you add the same number three times, the set only keeps one copy of it. Why use Python sets in your code? You need Python sets when you want to filter out duplicate data instantly. Imagine you have a list of one thousand user ids, but many people clicked the sign up button twice. If you put that list into a set, Python throws away the copies for you. This saves a lot of time and keeps your memory clean. You can check out Python Context Managers: How to Open Files and Manage Resources Safely to see how other tools protect your system resources. Lists keep the order of items and let you store the same value twenty times. Sets do not care about the order, and they ban duplicate values completely. This strict rule is what makes them so fast when you search …