Skip to main content

Python Sets

Python sets are a powerful data structure used to store an unordered collection of unique elements. They are particularly useful for membership testing, removing duplicates, and performing mathematical set operations like union, intersection, and difference.

Key Characteristics of Sets

  1. Unordered: The items in a set do not have a defined order.
  2. Unique Elements: A set automatically removes duplicate items.
  3. Mutable: Elements can be added or removed from a set.
  4. Heterogeneous: Elements of different types can coexist in a set.

Creating Sets

You can create a set using curly braces {} or the set() function.

# Using curly braces my_set = {1, 2, 3, 4, 5} print(my_set) # Output: {1, 2, 3, 4, 5} # Using the set() function my_set = set([1, 2, 3, 4, 5]) print(my_set) # Output: {1, 2, 3, 4, 5}


Basic Set Operations

Adding Elements

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}


Removing Elements

my_set = {1, 2, 3, 4, 5}
my_set.remove(4)  # Raises KeyError if 4 is not found
print(my_set)  # Output: {1, 2, 3, 5}

my_set.discard(3)  # Does not raise an error if 3 is not found
print(my_set)  # Output: {1, 2, 5}

# Remove an arbitrary element
my_set.pop()
print(my_set)  # Output: {2, 5} (output may vary)


Set Operations

Union

The union of two sets is a set containing all elements from both sets.

set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) print(union_set) # Output: {1, 2, 3, 4, 5} # Using the | operator union_set = set1 | set2 print(union_set) # Output: {1, 2, 3, 4, 5}


Intersection

The intersection of two sets is a set containing only the elements that are in both sets.

set1 = {1, 2, 3} set2 = {2, 3, 4} intersection_set = set1.intersection(set2) print(intersection_set) # Output: {2, 3} # Using the & operator intersection_set = set1 & set2 print(intersection_set) # Output: {2, 3}


Difference

The difference of two sets is a set containing elements that are in the first set but not in the second.

set1 = {1, 2, 3} set2 = {2, 3, 4} difference_set = set1.difference(set2) print(difference_set) # Output: {1} # Using the - operator difference_set = set1 - set2 print(difference_set) # Output: {1}

Symmetric Difference

The symmetric difference of two sets is a set containing elements that are in either set, but not in both.

set1 = {1, 2, 3} set2 = {2, 3, 4} symmetric_difference_set = set1.symmetric_difference(set2) print(symmetric_difference_set) # Output: {1, 4} # Using the ^ operator symmetric_difference_set = set1 ^ set2 print(symmetric_difference_set) # Output: {1, 4}


Other Useful Methods

  • issubset(): Check if one set is a subset of another.
  • issuperset(): Check if one set is a superset of another.
  • copy(): Create a shallow copy of a set.
set1 = {1, 2, 3}
set2 = {1, 2}
print(set2.issubset(set1))  # Output: True
print(set1.issuperset(set2))  # Output: True

# Copying a set
set3 = set1.copy()
print(set3)  # Output: {1, 2, 3}


Python sets are versatile and efficient for managing collections of unique elements. They offer a wide range of operations to perform set theory computations and are an essential tool in any Python programmer's toolkit.

Comments

Popular posts from this blog

Power BI tenant settings and admin portal

As of my last update, Power BI offers a dedicated admin portal for managing settings and configurations at the tenant level. Here's an overview of Power BI tenant settings and the admin portal: 1. Power BI Admin Portal: Access : The Power BI admin portal is accessible to users with admin privileges in the Power BI service. URL : You can access the admin portal at https://app.powerbi.com/admin-portal . 2. Tenant Settings: General Settings : Configure general settings such as tenant name, regional settings, and language settings. Tenant Administration : Manage user licenses, permissions, and access rights for Power BI within the organization. Usage Metrics : View usage metrics and reports to understand how Power BI is being used across the organization. Service Health : Monitor the health status of the Power BI service and receive notifications about service incidents and outages. Audit Logs : Access audit logs to track user activities, access requests, and administrative actions wit...

Understanding the Power BI ecosystem and workflow

Understanding the Power BI ecosystem and workflow involves getting familiar with the various components of Power BI and how they interact to provide a comprehensive data analysis and visualization solution. Here's a detailed explanation: Power BI Ecosystem The Power BI ecosystem consists of several interconnected components that work together to enable users to connect to data sources, transform and model data, create visualizations, and share insights. The main components are: Power BI Desktop Power BI Service Power BI Mobile Power BI Gateway Power BI Report Server Power BI Embedded PowerBI Workflow Here’s a typical workflow in the Power BI ecosystem: Step 1: Connect to Data Sources Power BI Desktop:  Connect to various data sources like Excel, SQL databases, cloud services, and more. Power BI Gateway:  If using on-premises data sources, install and configure the gateway for secure data transfer. Step 2: Data Transformation and Modeling Power BI Desktop:  Use Power Query...

DAX UPPER Function

The DAX UPPER function in Power BI is used to convert all characters in a text string to uppercase. This function is useful for standardizing text data, ensuring consistency in text values, and performing case-insensitive comparisons. Syntax: UPPER(<text>) <text>: The text string that you want to convert to uppercase. Purpose: The UPPER function helps ensure that text data is consistently formatted in uppercase. This can be essential for tasks like data cleaning, preparing text for comparisons, and ensuring uniformity in text-based fields. E xample: Suppose you have a table named "Customers" with a column "Name" that contains names in mixed case. You want to create a new column that shows all names in uppercase. UppercaseName = UPPER(Customers[Name]) Example Scenario: Assume you have the following "Customers" table: You can use the UPPER function as follows: Using the UPPER function, you can convert all names to uppercase: UppercaseName = ...