Python Sets and Set Manipulations -CL12

Python Sets and Set Manipulations



Sets have several key characteristics that make them useful. Firstly, sets are unordered, which means that the elements in a set have no specific order or sequence. Secondly, sets only contain unique elements, meaning that no duplicates are allowed within a set. This uniqueness property makes sets ideal for tasks that involve eliminating duplicate values or finding unique elements.

In Python programming, sets are represented using curly braces {} or the set() function. Python provides a built-in set data type that offers a range of operations and methods specifically designed for set manipulation. This makes sets a valuable tool for various data manipulation tasks such as filtering unique values, performing set operations, and checking for membership.

Sets in Python Kew points

Sets are unordered collections of unique elements:
Sets in Python are unordered collections, meaning that the elements in a set have no specific order or sequence. This distinguishes sets from other data structures like lists or tuples, which maintain the order of elements.

Sets can be created using curly braces {} or the set() function:
sets only contain unique elements. This means that duplicates are not allowed within a set. If you try to add a duplicate element to a set, it will be automatically ignored. This uniqueness property makes sets useful for tasks that involve eliminating duplicates or working with distinct values.

Understanding Python Sets

Creating a Set:
You can create a set in Python using curly braces {} or the set() function. Here are a few examples:

Example 1: Creating a set with curly braces:
python
my_set = {1, 2, 3} print(my_set) # Output: {1, 2, 3}

Example 2: Creating a set with the set() function:
python
my_set = set([4, 5, 6]) print(my_set) # Output: {4, 5, 6}

In the first example, a set is created by directly listing the elements inside curly braces. In the second example, the set() function is used to create a set by passing an iterable (in this case, a list) as an argument.

[ *In Python, an iterable is an object that can be looped over or iterated upon, such as lists, tuples, strings, or dictionaries. ]

Empty Set: 
To create an empty set in Python, you cannot use empty curly braces {} because it will create an empty dictionary instead. Instead, you need to use the set() function without any arguments.

Example: Creating an empty set:
python
empty_set = set() print(empty_set) # Output: set()

In this example, the set() function is called without any elements, resulting in an empty set being created.

It's important to note that sets cannot contain mutable elements like lists or dictionaries, but they can contain immutable elements like numbers, strings, or tuples. Sets automatically remove duplicate elements, ensuring that only unique elements are stored within the set.

Sets in Python Basic Video Guide



Set Operations in Python

Union:

The union() method and the | operator in Python are used for set union, which combines two sets into a new set that contains all the unique elements from both sets.

union() method: 
  • The union() method is a built-in method of sets in Python. It takes another set as an argument and returns a new set that contains all the elements from both sets without any duplicates.
Example:
python
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) print(union_set) # Output: {1, 2, 3, 4, 5}

| operator: 
  • The | operator can also be used to perform set union in Python. It combines two sets and returns a new set that contains all the unique elements from both sets.
Example:
python
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1 | set2 print(union_set) # Output: {1, 2, 3, 4, 5}

The union operation is useful when you want to combine the elements of multiple sets into a single set, while ensuring that duplicate elements are eliminated. It allows you to create a set that contains all the unique elements from the combined sets.


Intersection:

The intersection() method and the & operator in Python are used for set intersection, which finds the common elements between two sets.

intersection() method: 
  • The intersection() method is a built-in method of sets in Python. It takes another set as an argument and returns a new set that contains the elements present in both sets.
Example:
python
set1 = {1, 2, 3} set2 = {3, 4, 5} intersection_set = set1.intersection(set2) print(intersection_set) # Output: {3}

& operator: 
  • The & operator can also be used to perform set intersection in Python. It returns a new set that contains the common elements between the two sets.
Example:
python
set1 = {1, 2, 3} set2 = {3, 4, 5} intersection_set = set1 & set2 print(intersection_set) # Output: {3}

The intersection operation is helpful when you need to find the elements that are present in both sets. It allows you to identify the common elements shared by the sets and create a new set containing only those common elements.

Union and Intersection - Set Operations in Python Video Guide



Difference:

The difference() method and the - operator in Python are used for set difference, which finds the elements that are unique to a particular set compared to another set.

difference() method: 
  • The difference() method is a built-in method of sets in Python. It takes another set as an argument and returns a new set that contains the elements present in the original set but not in the argument set.
Example:
python
set1 = {1, 2, 3, 4} set2 = {3, 4, 5} difference_set = set1.difference(set2) print(difference_set) # Output: {1, 2}

- operator: 
  • The - operator can also be used to perform set difference in Python. It returns a new set that contains the elements present in the left operand set but not in the right operand set.

Example:
python
set1 = {1, 2, 3, 4} set2 = {3, 4, 5} difference_set = set1 - set2 print(difference_set) # Output: {1, 2}

The difference operation allows you to identify the elements that are unique to a particular set. It helps you find the elements present in one set but not in the other, allowing you to focus on the distinctive elements of each set.

In the provided examples, set1 has elements {1, 2, 3, 4}, and set2 has elements {3, 4, 5}. By performing the difference operation, we find that the elements {1, 2} are unique to set1, as they are present in set1 but not in set2.



Symmetric Difference:

The symmetric_difference() method and the ^ operator in Python are used for set symmetric difference, which finds the elements that are present in either of the sets but not in both.

symmetric_difference() method: 
  • The symmetric_difference() method is a built-in method of sets in Python. It takes another set as an argument and returns a new set that contains the elements that are present in either the original set or the argument set, but not in both.
Example:
python
set1 = {1, 2, 3} set2 = {3, 4, 5} symmetric_difference_set = set1.symmetric_difference(set2) print(symmetric_difference_set) # Output: {1, 2, 4, 5}

^ operator: 
  • The ^ operator can also be used to perform set symmetric difference in Python. It returns a new set that contains the elements that are present in either the left operand set or the right operand set, but not in both.
Example:
python
set1 = {1, 2, 3} set2 = {3, 4, 5} symmetric_difference_set = set1 ^ set2 print(symmetric_difference_set) # Output: {1, 2, 4, 5}

The symmetric difference operation allows you to identify the elements that are unique to either of the sets. It helps you find the elements that exist in one set or the other, but not in both, highlighting the differences between the sets.

In the provided examples, set1 has elements {1, 2, 3}, and set2 has elements {3, 4, 5}. By performing the symmetric difference operation, we find that the elements {1, 2, 4, 5} are present in either set1 or set2, but not in both.

Difference and Symmetric Difference - Set Operations in Python Video Guide



Set manipulations

Set manipulations refer to the operations and techniques used to modify, combine, compare, and extract information from sets in order to perform various data manipulation tasks efficiently.

Subset and Superset:

In Python, sets have two methods for checking subset and superset relationships: issubset() and issuperset().

issubset() method: 
  • The issubset() method is a built-in method of sets in Python. It takes another set as an argument and returns True if the original set is a subset of the argument set, meaning that all elements of the original set are also present in the argument set.
Example:
python
set1 = {1, 2, 3} set2 = {1, 2, 3, 4, 5} subset_check = set1.issubset(set2) print(subset_check) # Output: True

In this example, set1 is a subset of set2 because all the elements of set1 (1, 2, and 3) are also present in set2.


issuperset() method: 
  • The issuperset() method is a built-in method of sets in Python. It takes another set as an argument and returns True if the original set is a superset of the argument set, meaning that the original set contains all the elements present in the argument set.
Example:
python
set1 = {1, 2, 3, 4, 5} set2 = {1, 2, 3} superset_check = set1.issuperset(set2) print(superset_check) # Output: True

In this example, set1 is a superset of set2 because set1 contains all the elements of set2.

These methods are useful for determining the subset or superset relationship between sets. They allow you to check if one set is entirely contained within another or if one set contains all the elements of another set.


issubset() and issuperset() output False example

Here's an example where both the issubset() and issuperset() methods return False:
python
set1 = {1, 2, 3} set2 = {4, 5, 6} subset_check = set1.issubset(set2) superset_check = set1.issuperset(set2) print(subset_check) # Output: False print(superset_check) # Output: False

In this example, set1 and set2 have no common elements. Thus, set1 is not a subset of set2, as set2 does not contain all the elements of set1. Similarly, set1 is not a superset of set2, as set1 does not contain all the elements of set2. Therefore, both the issubset() and issuperset() methods return False in this case.

By using the issubset() and issuperset() methods, you can easily verify the subset or superset relationship between sets in your Python programs.

issubset(), issuperset() - Set Operations in Python Video Guide


Set Membership:

In Python, you can use the in and not in operators to check if an element belongs to a set.

in operator: 
  • The in operator returns True if the specified element is present in the set; otherwise, it returns False.
Example:
python
my_set = {1, 2, 3, 4} print(2 in my_set) # Output: True print(5 in my_set) # Output: False

In this example, we check if the elements 2 and 5 are present in the set my_set. The first print statement returns True because 2 is present in the set, while the second print statement returns False because 5 is not present in the set.

not in operator: 
  • The not in operator returns True if the specified element is not present in the set; otherwise, it returns False.
Example:
python
my_set = {1, 2, 3, 4} print(2 not in my_set) # Output: False print(5 not in my_set) # Output: True

In this example, we use the not in operator to check if the elements 2 and 5 are not present in the set my_set. The first print statement returns False because 2 is present in the set, while the second print statement returns True because 5 is not present in the set.

These membership operators (in and not in) are handy when you want to determine whether an element is present in a set or not. They provide a convenient way to perform membership testing in Python sets, allowing you to easily check for the presence or absence of elements.


Set Operations with Assignment:

In Python, you can perform in-place set operations using assignment operators like |=, &=, -=, and ^=. These operators combine set operations with assignment, allowing you to modify a set in place.

|= operator (Union with Assignment): 
  • The |= operator performs a union operation and assigns the result back to the original set. It adds all the elements from the right operand set to the left operand set, eliminating duplicates.
Example:
python
set1 = {1, 2, 3} set2 = {3, 4, 5} set1 |= set2 print(set1) # Output: {1, 2, 3, 4, 5}

In this example, the |= operator is used to perform the union operation between set1 and set2. The resulting set {1, 2, 3, 4, 5} is assigned back to set1.

&= operator (Intersection with Assignment): 
  • The &= operator performs an intersection operation and assigns the result back to the original set. It retains only the elements that are common to both sets.
Example:
python
set1 = {1, 2, 3} set2 = {3, 4, 5} set1 &= set2 print(set1) # Output: {3}

In this example, the &= operator is used to perform the intersection operation between set1 and set2. The resulting set {3} is assigned back to the set1.

-= operator (Difference with Assignment): 
  • The -= operator performs a difference operation and assigns the result back to the original set. It removes the elements from the left operand set that are also present in the right operand set.
Example:
python
set1 = {1, 2, 3, 4} set2 = {3, 4, 5} set1 -= set2 print(set1) # Output: {1, 2}

In this example, the -= operator is used to perform the difference operation between set1 and set2. The resulting set {1, 2} is assigned back to set1.

^= operator (Symmetric Difference with Assignment): 
  • The ^= operator performs a symmetric difference operation and assigns the result back to the original set. It retains only the elements that are present in either of the sets but not in both.
Example:
python
set1 = {1, 2, 3} set2 = {3, 4, 5} set1 ^= set2 print(set1) # Output: {1, 2, 4, 5}

In this example, the ^= operator is used to perform the symmetric difference operation between set1 and set2. The resulting set {1, 2, 4, 5} is assigned back to set1.

These in-place set operations with assignment allow you to modify a set directly without creating a new set. They are useful when you want to update a set based on the result of a set operation, providing a concise and efficient way to modify sets in place.


Set Comprehension:

Set comprehension is a concise and powerful feature in Python that allows you to create sets based on existing sets or iterables. It follows a similar syntax to list comprehension but generates sets instead. Set comprehension provides a convenient way to construct sets in a single line of code, avoiding the need for explicit loops.

The general syntax for set comprehension is:
python
new_set = {expression for item in iterable if condition}

  • expression represents the value or operation to be performed on each item.
  • item is the variable that iterates over the elements in the iterable.
  • iterable is the sequence, collection, or iterator that provides the elements.
  • condition (optional) is an optional filtering condition that determines whether an item is included in the resulting set.

Example 1: Creating a set of squared numbers from a list using set comprehension.
python
numbers = [1, 2, 3, 4, 5] squared_set = {x**2 for x in numbers} print(squared_set) # Output: {1, 4, 9, 16, 25}

In this example, set comprehension is used to create a new set squared_set that contains the squared values of each element in the numbers list.

Example 2: Filtering a set to include only even numbers using set comprehension.
python
my_set = {1, 2, 3, 4, 5, 6} even_set = {x for x in my_set if x % 2 == 0} print(even_set) # Output: {2, 4, 6}

In this example, set comprehension is used to create a new set even_set that includes only the even numbers from the original set my_set by applying the condition x % 2 == 0.

Set comprehension provides a concise and readable way to create sets by transforming or filtering elements from existing sets or iterables. It offers flexibility and convenience in constructing sets in a single line, making your code more expressive and efficient.

Set Comprehension in Python Video Guide



Python Quizzes: String Formatting in Python. Test Your Memory

Here are 15 quizzes based on the topics covered in the post: 


Question 1:  What are sets in Python?

a) Ordered collections of elements

b) Unordered collections of unique elements

c) Mutable collections of elements

d) Immutable collections of unique elements


Question 2:  Which operator is used for set union in Python?

a) |

b) &

c) -

d) ^


Question 3:  How do you check if an element belongs to a set in Python?

a) using the contains() method

b) using the in operator

c) using the exists() method

d) using the is_member() function


Question 4:  What is the result of set1 |= set2 in Python?

a) Intersection of set1 and set2

b) Union of set1 and set2

c) Difference between set1 and set2

d) Symmetric difference between set1 and set2


Question 5:  Which method is used to check if one set is a subset of another in Python?

a) issubset()

b) issuperset()

c) subset()

d) superset()


Question 6:  What is the purpose of set comprehension in Python?

a) Creating ordered collections of elements

b) Filtering elements in a set based on a condition

c) Sorting elements in a set

d) Concatenating multiple sets


Question 7:  Which method is used to find the elements unique to a particular set in Python?

a) difference()

b) intersection()

c) symmetric_difference()

d) union()


Question 8:  What is the output of the following code snippet?


python
set1 = {1, 2, 3} set2 = {3, 4, 5} set1 -= set2 print(set1)

a) {1, 2, 3}

b) {4, 5}

c) {1, 2}

d) {3}


Question 9:  Which operator is used for set intersection in Python?

a) |

b) &

c) -

d) ^


Question 10:  How do you create an empty set in Python?

a) set()

b) {}

c) {0}

d) {''}


Question 11:  What does the not in operator do in Python?

a) Checks if an element is present in a set

b) Checks if an element is not present in a set

c) Checks if a set is empty

d) Checks if two sets are equal


Question 12:  What is the purpose of set union in Python?

a) To combine elements from two sets

b) To find the common elements between two sets

c) To find the elements unique to a particular set

d) To find the difference between two sets


Question 13:  Which method is used to check if one set is a superset of another in Python?

a) issubset()

b) issuperset()

c) subset()

d) superset()


Question 14:  What is the output of the following code snippet?


python
my_set = {1, 2, 3, 4, 5} print(3 in my_set)

a) True

b) False

c) Error

d) None


Question 15:  Which operator is used for set symmetric difference in Python?

a) |

b) &

c) -

d) ^



Question 1:  What are sets in Python?

a) Ordered collections of elements

b) Unordered collections of unique elements

c) Mutable collections of elements

d) Immutable collections of unique elements

Correct answer:  b) Unordered collections of unique elements


Question 2:  Which operator is used for set union in Python?

a) |

b) &

c) -

d) ^

Correct answer:  a) |


Question 3:  How do you check if an element belongs to a set in Python?

a) using the contains() method

b) using the in operator

c) using the exists() method

d) using the is_member() function

Correct answer:  b) using the in operator


Question 4:  What is the result of set1 |= set2 in Python?

a) Intersection of set1 and set2

b) Union of set1 and set2

c) Difference between set1 and set2

d) Symmetric difference between set1 and set2

Correct answer:  b) Union of set1 and set2


Question 5:  Which method is used to check if one set is a subset of another in Python?

a) issubset()

b) issuperset()

c) subset()

d) superset()

Correct answer:  a) issubset()


Question 6:  What is the purpose of set comprehension in Python?

a) Creating ordered collections of elements

b) Filtering elements in a set based on a condition

c) Sorting elements in a set

d) Concatenating multiple sets

Correct answer:  b) Filtering elements in a set based on a condition


Question 7:  Which method is used to find the elements unique to a particular set in Python?

a) difference()

b) intersection()

c) symmetric_difference()

d) union()

Correct answer:  c) symmetric_difference()


Question 8:  What is the output of the following code snippet?


python
set1 = {1, 2, 3} set2 = {3, 4, 5} set1 -= set2 print(set1)

a) {1, 2, 3}

b) {4, 5}

c) {1, 2}

d) {3}

Correct answer:  c) {1, 2}


Question 9:  Which operator is used for set intersection in Python?

a) |

b) &

c) -

d) ^

Correct answer:  b) &


Question 10:  How do you create an empty set in Python?

a) set()

b) {}

c) {0}

d) {''}

Correct answer:  a) set()


Question 11:  What does the not in operator do in Python?

a) Checks if an element is present in a set

b) Checks if an element is not present in a set

c) Checks if a set is empty

d) Checks if two sets are equal

Correct answer:  b) Checks if an element is not present in a set


Question 12:  What is the purpose of set union in Python?

a) To combine elements from two sets

b) To find the common elements between two sets

c) To find the elements unique to a particular set

d) To find the difference between two sets

Correct answer:  a) To combine elements from two sets


Question 13:  Which method is used to check if one set is a superset of another in Python?

a) issubset()

b) issuperset()

c) subset()

d) superset()

Correct answer:  b) issuperset()


Question 14:  What is the output of the following code snippet?


python
my_set = {1, 2, 3, 4, 5} print(3 in my_set)

a) True

b) False

c) Error

d) None

Correct answer:  a) True


Question 15:  Which operator is used for set symmetric difference in Python?

a) |

b) &

c) -

d) ^

Correct answer:  d) ^


I hope you find these quizzes helpful for reinforcing the concepts discussed in the post!



Post a Comment

Previous Post Next Post