Lesson · 40 min · Free
Python Sets Essentials
Python Sets Essentials body { font-family: sans-serif; line-height: 1.6; margin: 20px; } h1, h2 { color: #2c3e50; } pre { background-color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; } code { font-fami
Python Sets Essentials
Welcome to this lesson on Python Sets! In the realm of pharmacy and biotechnology, managing unique data points, such as a list of active pharmaceutical ingredients (APIs) in a compound, or distinct genetic markers identified in a study, is a common task. Python's built-in set data type is perfectly suited for these scenarios, offering an efficient way to store collections of unique, unordered items. A set is an unordered collection of unique elements. This means two important things: first, items in a set do not have a defined order, so you cannot access them by index. Second, and crucially for many scientific applications, a set automatically eliminates duplicate entries. If you try to add an item that already exists in the set, it simply won't be added again. Sets are mutable, meaning you can add or remove elements after creation. They are also highly optimized for checking membership (i.e., quickly determining if an item is present in the set) and performing mathematical set operations like union, intersection, and difference, which are invaluable for data analysis in scientific research.
Creating and Manipulating Sets
Sets can be created in a couple of ways. You can define a set by enclosing comma-separated elements within curly braces {} , or by using the set() constructor, particularly useful for converting other iterables like lists or tuples into sets. Remember, an empty set must be created using set() , as {} creates an empty dictionary. # Creating a set of unique drug codes drug_codes_1 = {"API001", "API002", "API003", "API001"} print(f"Initial drug codes set: {drug_codes_1}") # Output: {'API002', 'API003', 'API001'} (order may vary) # Creating a set from a list of patient IDs, demonstrating uniqueness patient_ids_list = [101, 102, 103, 101, 104] unique_patient_ids = set(patient_ids_list) print(f"Unique patient IDs: {unique_patient_ids}") # Output: {101, 102, 103, 104} # Adding elements to a set active_compounds = {"CompoundA", "CompoundB"} active_compounds.add("CompoundC") active_compounds.add("CompoundA") # Adding an existing element has no effect print(f"Active compounds after adding: {active_compounds}") # Output: {'CompoundA', 'CompoundB', 'CompoundC'} # Removing elements from a set active_compounds.remove("CompoundB") # Raises KeyError if element not found print(f"Active compounds after removing CompoundB: {active_compounds}") active_compounds.discard("CompoundD") # Does nothing if element not found print(f"Active compounds after discarding CompoundD: {active_compounds}") Beyond simple addition and removal, sets excel in performing mathematical operations. These operations are particularly useful in bioinformatics for comparing gene sets, or in pharmaceutical research for analyzing commonalities and differences between drug formulations or experimental results. Union ( | or .union() ): Returns a new set containing all unique elements from both sets. Intersection ( & or .intersection() ): Returns a new set containing only the elements common to both sets. Difference ( - or .difference() ): Returns a new set containing elements present in the first set but not in the second. Symmetric Difference ( ^ or .symmetric_difference() ): Returns a new set containing elements that are in either set, but not in both. # Example: Comparing gene sets for different disease phenotypes genes_disease_A = {"Gene1", "Gene2", "Gene3", "Gene4"} genes_disease_B = {"Gene3", "Gene4", "Gene5", "Gene6"} # Genes associated with either disease A or disease B (Union) all_relevant_genes = genes_disease_A.union(genes_disease_B) print(f"Genes relevant to either disease: {all_relevant_genes}") # Output: {'Gene1', 'Gene2', 'Gene3', 'Gene4', 'Gene5', 'Gene6'} # Genes common to both diseases (Intersection) common_genes = genes_disease_A.intersection(genes_disease_B) print(f"Genes common to both diseases: {common_genes}") # Output: {'Gene3', 'Gene4'} # Genes specific to disease A (Difference) specific_to_disease_A = genes_disease_A.difference(genes_disease_B) print(f"Genes specific to Disease A: {specific_to_disease_A}") # Output: {'Gene1', 'Gene2'} # Genes unique to either disease, but not common to both (Symmetric Difference) unique_to_either_disease = genes_disease_A.symmetric_difference(genes_disease_B) print(f"Genes unique to either disease (not common): {unique_to_either_disease}") # Output: {'Gene1', 'Gene2', 'Gene5', 'Gene6'}
Key Takeaways
Sets are unordered collections of unique elements. They are mutable, allowing elements to be added or removed. Sets automatically handle duplicate removal, ensuring only unique items are stored. They provide efficient methods for membership testing and mathematical set operations (union, intersection, difference). Use curly braces {} for non-empty sets, and set() for empty sets or converting other iterables.
Practice Exercise
You are analyzing a batch of patient samples. You have two lists of unique identifiers for samples collected at two different time points. samples_timepoint_1 = ["S001", "S003", "S005", "S007", "S009"] and samples_timepoint_2 = ["S002", "S003", "S006", "S007", "S010"] . Convert these lists into sets. Then, write Python code to find: All unique sample identifiers collected across both time points. Sample identifiers that were collected at both time points. Sample identifiers that were collected only at time point 1 (not at time point 2). Print the results for each operation.
Watch the full lesson — free
This topic is part of Python Programming - Basics, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →