Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python - Set

A set is a mutable collection of distinct hashable objects, same as the list and tuple. It is an unordered collection of objects, meaning it does not record element position or order of insertion and so cannot access elements using indexes.

The set is a Python implementation of the set in Mathematics. A set object has suitable methods to perform mathematical set operations like union, intersection, difference, etc.

A set object contains one or more items, not necessarily of the same type, which are separated by a comma and enclosed in curly brackets . The following defines a set object with even numbers.

Example: Python Set Object
even_nums = {2, 4, 6, 8, 10} # set of even numbers
emp = {1, 'Steve', 10.5, True} # set of different objects
Try it

A set doesn't store duplicate objects. Even if an object is added more than once inside the curly brackets, only one copy is held in the set object. Hence, indexing and slicing operations cannot be done on a set object.

Example: Set of Distinct Elements
nums = {1, 2, 2, 3, 4, 4, 5, 5}
print(nums) #output: {1, 2, 3, 4, 5}
Try it

The order of elements in the set is not necessarily the same as the order given at the time of assignment. Python optimizes the structure of a set for performing operations over it, as defined in mathematics.

Only immutable (and hashable) objects can be a part of a set object. Numbers (integer, float, as well as complex), strings, and tuple objects are accepted, but set, list, and dictionary objects are not.

Example: Set Elements
myset = {(10,10), 10, 20}
print(myset)

myset = {[10, 10], 10, 20}  #TypeError can't add a list

myset = { {10, 10}, 10, 20} #TypeError can't add a set
Try it

In the above example, (10,10) is a tuple, hence it becomes part of the set. However, [10,10] is a list, hence an error message is displayed saying that the list is unhashable. (Hashing is a mechanism in computer science which enables quicker search of objects in the computer's memory.)

Even though mutable objects are not stored in a set, the set itself is a mutable object.

Use the set() function to create an empty set. Empty curly braces will create an empty dictionary instead of an empty set.

Example: Creating an Empty Set
emp = {} # creates an empty dictionary
print(type(emp)) #<class 'dict'>

s = set() # creates an empty set
print(type(s)) #<class 'set'>
Try it

The set() function also use to convert string, tuple, or dictionary object to a set object, as shown below.

Example: Convert Sequence to Set
s = set('Hello') # converts string to set
print(s) #output: {'l', 'H', 'o', 'e'}

s = set((1,2,3,4,5)) # converts tuple to set
print(s) #output: {1, 2, 3, 4, 5}

d = {1:'One', 2: 'Two'} 
s = set(d) # converts dict to set
print(s) #{1, 2}
Try it

Modify Set Elements

Use built-in set functions add(), remove() or update() methods to modify set collection.

Example:
s = set() # creates an empty set
s.add(10) # add an element
s.add(20)
s.add(30)
print(s) #output: {10, 20, 30}

primeNums = {2, 3, 5, 7}
s.update(primeNums) # update set with another set
print(s)  #output:{2, 3, 20, 5, 7, 10, 30}

s.remove(2) # remove an element
print(s)  #output:{3, 20, 5, 7, 10, 30}
Try it

Set Operations

As mentioned earlier, the set data type in Python implements as the set defined in mathematics. Various set operations can be performed. Operators |, &, - and ^ perform union, intersection, difference, and symmetric difference operations, respectively. Each of these operators has a corresponding method associated with the built-in set class.

OperationExample
Union: Returns a new set with elements from both the sets.

Operator: |
Method: set.union()
s1=5s2=8s1|s2 #8
Try it
s1=5s2=8s1.union(s2)  #8s2.union(s1)  #8
Try it
Intersection: Returns a new set containing elements common to both sets.

Operator: &
Method: set.intersection()
s1=5s2=8s1&s2 #5s2&s1 #5
Try it
s1=5s2=8s1.intersection(s2)  #5s2.intersection(s1)  #5
Try it
Difference: Returns a set containing elements only in the first set, but not in the second set.

Operator: -
Method: set.difference()
s1=5s2=8s1-s2  #3s2-s1  #7
Try it
s1=5s2=8s1.difference(s2) #3s2.difference(s1) #7
Try it
Symmetric Difference: Returns a set consisting of elements in both sets, excluding the common elements.

Operator: ^
Method: set.symmetric_difference()
s1=5s2=8s1^s2 #8s2^s1 #8
Try it
s1=5s2=8s1.symmetric_difference(s2)  #8s2.symmetric_difference(s1)  #8
Try it

Set Methods

The following table lists built-in set methods:

MethodDescription
set.add()Adds an element to the set. If an element is already exist in the set, then it does not add that element.
set.clear()Removes all the elements from the set.
set.copy()Returns a shallow copy of the set.
set.difference()Returns the new set with the unique elements that are not in the another set passed as a parameter.
set.difference_update()Updates the set on which the method is called with the elements that are common in another set passed as an argument.
set.discard()Removes a specific element from the set.
set.intersection()Returns a new set with the elements that are common in the given sets.
set.intersection_update()Updates the set on which the instersection_update() method is called, with common elements among the specified sets.
set.isdisjoint()Returns true if the given sets have no common elements. Sets are disjoint if and only if their intersection is the empty set.
set.issubset()Returns true if the set (on which the issubset() is called) contains every element of the other set passed as an argument.
set.pop()Removes and returns a random element from the set.
set.remove()Removes the specified element from the set. If the specified element not found, raise an error.
set.symmetric_difference()Returns a new set with the distinct elements found in both the sets.
set.symmetric_difference_update()Updates the set on which the instersection_update() method called, with the elements that are common among the specified sets.
set.union()Returns a new set with distinct elements from all the given sets.
set.update()Updates the set by adding distinct elements from the passed one or more iterables.
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.