Python SetA Python set is the collection of the unordered items. Each element in the set must be unique, immutable, and the sets remove the duplicate elements. Sets are mutable which means we can modify it after its creation. Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot directly access any element of the set by the index. However, we can print them all together, or we can get the list of elements by looping through the set. Creating a setThe set can be created by enclosing the comma-separated immutable items with the curly braces {}. Python also provides the set() method, which can be used to create the set by the passed sequence. Example 1: Using curly bracesOutput: {'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'} Example 2: Using set() methodOutput: {'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'} It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary, set) can't be a member of set. Consider the following example. Output:
In the above code, we have created two sets, the set set1 have immutable elements and set2 have one mutable element as a list. While checking the type of set2, it raised an error, which means set can contain only immutable elements. Creating an empty set is a bit different because empty curly {} braces are also used to create a dictionary as well. So Python provides the set() method used without an argument to create an empty set. Output: Let's see what happened if we provide the duplicate element to the set. Output: Return set with unique elements: {1, 2, 4, 5, 8, 9, 10} In the above code, we can see that set5 consisted of multiple duplicate elements when we printed it remove the duplicity from the set. Adding items to the setPython provides the add() method and update() method which can be used to add some particular item to the set. The add() method is used to add a single element whereas the update() method is used to add multiple elements to the set. Consider the following example. Example: 1 - Using add() methodOutput: printing the original set ... {'February', 'May', 'April', 'March', 'June', 'January'} Adding other months to the set... Printing the modified set... {'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'} looping through the set elements ... February July May April March August June January To add more than one item in the set, Python provides the update() method. It accepts iterable as an argument. Consider the following example. Example - 2 Using update() functionOutput: printing the original set ... {'January', 'February', 'April', 'May', 'June', 'March'} updating the original set ... printing the modified set ... {'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'} Removing items from the setPython provides the discard() method and remove() method which can be used to remove the items from the set. The difference between these function, using discard() function if the item does not exist in the set then the set remain unchanged whereas remove() method will through an error. Consider the following example. Example-1 Using discard() methodOutput: printing the original set ... {'February', 'January', 'March', 'April', 'June', 'May'} Removing some months from the set... Printing the modified set... {'February', 'March', 'April', 'June'} looping through the set elements ... February March April June Python provides also the remove() method to remove the item from the set. Consider the following example to remove the items using remove() method. Example-2 Using remove() functionOutput: printing the original set ... {'February', 'June', 'April', 'May', 'January', 'March'} Removing some months from the set... Printing the modified set... {'February', 'June', 'April', 'March'} We can also use the pop() method to remove the item. Generally, the pop() method will always remove the last item but the set is unordered, we can't determine which element will be popped from set. Consider the following example to remove the item from the set using pop() method. Output: printing the original set ... {'June', 'January', 'May', 'April', 'February', 'March'} Removing some months from the set... Printing the modified set... {'May', 'April', 'February', 'March'} In the above code, the last element of the Month set is March but the pop() method removed the June and January because the set is unordered and the pop() method could not determine the last element of the set. Python provides the clear() method to remove all the items from the set. Consider the following example. Output: printing the original set ... {'January', 'May', 'June', 'April', 'March', 'February'} Removing all the items from the set... Printing the modified set... set() Difference between discard() and remove()Despite the fact that discard() and remove() method both perform the same task, There is one main difference between discard() and remove(). If the key to be deleted from the set using discard() doesn't exist in the set, the Python will not give the error. The program maintains its control flow. On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the Python will raise an error. Consider the following example. Example-Output: printing the original set ... {'March', 'January', 'April', 'June', 'February', 'May'} Removing items through discard() method... printing the modified set... {'March', 'January', 'April', 'June', 'February', 'May'} Removing items through remove() method... Traceback (most recent call last): File "set.py", line 9, in Months.remove("Jan") KeyError: 'Jan' Python Set OperationsSet can be performed mathematical operation such as union, intersection, difference, and symmetric difference. Python provides the facility to carry out these operations with operators or methods. We describe these operations as follows. Union of two SetsThe union of two sets is calculated by using the pipe (|) operator. The union of the two sets contains all the items that are present in both the sets. ![]() Consider the following example to calculate the union of two sets. Example 1: using union | operator Output: {'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'} Python also provides the union() method which can also be used to calculate the union of two sets. Consider the following example. Example 2: using union() method Output: {'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'} Intersection of two setsThe intersection of two sets can be performed by the and & operator or the intersection() function. The intersection of the two sets is given as the set of the elements that common in both sets. ![]() Consider the following example. Example 1: Using & operator Output: {'Monday', 'Tuesday'} Example 2: Using intersection() method Output: {'Martin', 'David'} Example 3: Output: {1,2,5} The intersection_update() methodThe intersection_update() method removes the items from the original set that are not present in both the sets (all the sets if more than one are specified). The intersection_update() method is different from the intersection() method since it modifies the original set by removing the unwanted items, on the other hand, the intersection() method returns a new set. Consider the following example. Output: {'castle'} Difference between the two setsThe difference of two sets can be calculated by using the subtraction (-) operator or intersection() method. Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be obtained that element of A, which is not present in the set B. ![]() Consider the following example. Example 1 : Using subtraction ( - ) operator Output: {'Thursday', 'Wednesday'} Example 2 : Using difference() method Output: {'Thursday', 'Wednesday'} Symmetric Difference of two setsThe symmetric difference of two sets is calculated by ^ operator or symmetric_difference() method. Symmetric difference of sets, it removes that element which is present in both sets. Consider the following example: ![]() Example - 1: Using ^ operator Output: {3, 4, 5, 6, 8, 9, 10} Example - 2: Using symmetric_difference() method Output: {3, 4, 5, 6, 8, 9, 10} Set comparisonsPython allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which we can check whether a set is a subset, superset, or equivalent to other set. The boolean true or false is returned depending upon the items present inside the sets. Consider the following example. Output: True False False FrozenSetsThe frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set cannot be changed and therefore it can be used as a key in the dictionary. The elements of the frozen set cannot be changed after the creation. We cannot change or append the content of the frozen sets by using the methods like add() or remove(). The frozenset() method is used to create the frozenset object. The iterable sequence is passed into this method which is converted into the frozen set as a return type of the method. Consider the following example to create the frozen set. Output:
Frozenset for the dictionaryIf we pass the dictionary as the sequence inside the frozenset() method, it will take only the keys from the dictionary and returns a frozenset that contains the key of the dictionary as its elements. Consider the following example. Output:
Set Programming ExampleExample - 1: Write a program to remove the given number from the set. Output: Enter the number you want to remove:12 After Removing: {1, 2, 3, 4, 5, 6, 24} Example - 2: Write a program to add multiple elements to the set. Output: {1, 2, 4, 'Apple', 'John', 'CS', 'Mango', 'Grapes'} Example - 3: Write a program to find the union between two set. Output: {96, 65, 2, 'Joseph', 1, 'Peter', 59} Example- 4: Write a program to find the intersection between two sets. Output: {56, 23} Example - 5: Write the program to add element to the frozenset. Output: TypeError: 'frozenset' object does not support item assignment Above code raised an error because frozensets are immutable and can't be changed after creation. Example - 6: Write the program to find the issuperset, issubset and superset. Output: False False True True Python Built-in set methodsPython contains the following methods to be used with the sets.
Next TopicPython Dictionary
|
Python tutorial provides basic and advanced concepts of Python.
Vue.js is an open-source progressive JavaScript framework
HTML refers to Hypertext Markup Language. HTML is the gateway ...
Java is an object-oriented, class-based computer-programming language.
PHP is an open-source,interpreted scripting language.
Spring is a lightweight framework.Spring framework makes ...
JavaScript is an scripting language which is lightweight and cross-platform.
CSS refers to Cascading Style Sheets...
jQuery is a small and lightweight JavaScript library. jQuery ...
SQL is used to perform operations on the records stored in the database.
C programming is considered as the base for other programming languages.
JavaScript is an scripting language which is lightweight and cross-platform.
Vue.js is an open-source progressive JavaScript framework
ReactJS is a declarative, efficient, and flexible JavaScript library.
jQuery is a small and lightweight JavaScript library. jQuery ...
Node.js is a cross-platform environment and library for running JavaScript app...
TypeScript is a strongly typed superset of JavaScript which compiles to plain JavaScript.
Angular JS is an open source JavaScript framework by Google to build web app...
JSON is lightweight data-interchange format.
AJAX is an acronym for Asynchronous JavaScript and XML.
ES6 or ECMAScript 6 is a scripting language specification ...
Angular 7 is completely based on components.
jQuery UI is a set of user interface interactions built on jQuery...
Python tutorial provides basic and advanced concepts of Python.
Java is an object-oriented, class-based computer-programming language.
Node.js is a cross-platform environment and library for running JavaScript app...
PHP is an open-source,interpreted scripting language.
Go is a programming language which is developed by Google...
C programming is considered as the base for other programming languages.
C++ is an object-oriented programming language. It is an extension to C programming.
C# is a programming language of .Net Framework.
Ruby is an open-source and fully object-oriented programming language.
JSP technology is used to create web application just like Servlet technology.
The JSTL represents a set of tags to simplify the JSP development.
ASP.NET is a web framework designed and developed by Microsoft.
Perl is a cross-platform environment and library for running JavaScript...
Scala is an object-oriented and functional programming language.
VBA stands for Visual Basic for Applications.
Spring is a lightweight framework.Spring framework makes ...
Spring Boot is a Spring module that provides the RAD feature...
Django is a Web Application Framework which is used to develop web applications.
Servlet technology is robust and scalable because of java language.
The Struts 2 framework is used to develop MVC based web applications.
Hibernate is an open source, lightweight, ORM tool.
Solr is a scalable, ready-to-deploy enterprise search engine.
SQL is used to perform operations on the records stored in the database.
MySQL is a relational database management system based...
Oracle is a relational database management system.
SQL Server is software developed by Microsoft.
PostgreSQL is an ORDBMS.
DB2 is a database server developed by IBM.
Redis is a No SQL database which works on the concept of key-value pair.
SQLite is embedded relational database management system.
MongoDB is a No SQL database. It is an document-oriented database...
Memcached is a free, distributed memory object caching system.
Hibernate is an open source, lightweight, ORM tool.
PL/SQL is a block structured language that can have multiple blocks in it.
DBMS Tutorial is software that is used to manage the database.
Spark is a unified analytics engine for large-scale data processing...
IntelliJ IDEA is an IDE for Java Developers which is developed by...
Git is a modern and widely used distributed version control system in the world.
GitHub is an immense platform for code hosting.
SVN is an open-source centralized version control system.
Maven is a powerful project management tool that is based on POM.
Jsoup is a java html parser.
UML is a general-purpose, graphical modeling language.
RESTful Web Services are REST Architecture based Web Services.
Postman is one testing tools which is used for API testing.
JMeter is to analyze the performance of web application.
Jenkins builds and tests our software projects.
SEO stands for Search Engine Optimization.
MATLAB is a software package for mathematical computation, visualization...
Unity is an engine for creating games on multiple platforms.
Hadoop is an open source framework.
Pig is a high-level data flow platform for executing Map Reduce programs of Hadoop.
Spark is a unified analytics engine for large-scale data processing...
Spring Cloud is a framework for building robust cloud applications.
Spring Boot is a Spring module that provides the RAD feature...
AI is one of the fascinating and universal fields of Computer.
Cloud computing is a virtualization-based technology.
AWS stands for Amazon Web Services which uses distributed IT...
Microsoft Azure is a cloud computing platform...
IoT stands for Internet of Things...
Spring Cloud is a framework for building robust cloud applications.
Email:jjw.quan@gmail.com