banner



How To Create Set In Python

next → ← prev

Python Set

A Python set is the collection of the unordered items. Each chemical element in the set must be unique, immutable, and the sets remove the duplicate elements. Sets are mutable which means we tin can modify it after its cosmos.

Unlike other collections in Python, there is no alphabetize attached to the elements of the set, i.due east., we cannot directly access whatsoever chemical element of the set by the index. However, we can impress them all together, or nosotros can get the listing of elements past looping through the gear up.

Creating a set up

The set can be created past 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.

Instance i: Using curly braces

Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Th', 'Sunday', 'Wednesday'} <class 'set'> looping through the set elements ...  Friday Tuesday Monday Sat Thursday Sunday Wednesday          

Instance 2: Using set up() method

Output:

{'Friday', 'Wednesday', 'Th', 'Saturday', 'Monday', 'Tuesday', 'Sunday'} <class 'set'> looping through the set up elements ...  Friday Wednesday Th Sabbatum Monday Tuesday Sun          

It can contain whatsoever type of element such as integer, bladder, tuple etc. But mutable elements (listing, lexicon, set) can't exist a member of ready. Consider the following example.

Output:

<class 'set'>  Traceback (well-nigh recent call last) <ipython-input-v-9605bb6fbc68> in <module>       4        5 #Creating a gear up which holds mutable elements ----> six set2 = {1,2,three,["Javatpoint",four]}       7 impress(type(set2))  TypeError: unhashable blazon: 'listing'          

In the to a higher place code, we take created two sets, the set set1 have immutable elements and set2 have one mutable chemical 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 gear up is a fleck dissimilar because empty curly {} braces are likewise used to create a dictionary equally well. Then Python provides the set() method used without an argument to create an empty prepare.

Output:

<class 'dict'> <class 'fix'>          

Let'south run into what happened if we provide the duplicate element to the set.

Output:

Return set with unique elements: {i, two, 4, 5, viii, nine, 10}          

In the in a higher place code, we tin can see that set5 consisted of multiple indistinguishable elements when we printed it remove the duplicity from the ready.

Calculation items to the set

Python provides the add() method and update() method which tin can be used to add some particular particular to the set. The add together() method is used to add together a single element whereas the update() method is used to add multiple elements to the prepare. Consider the post-obit example.

Example: 1 - Using add() method

Output:

press the original set ...  {'February', 'May', 'April', 'March', 'June', 'Jan'}  Calculation other months to the ready...  Printing the modified set... {'February', 'July', 'May', 'Apr', 'March', 'Baronial', 'June', 'Jan'}  looping through the set elements ...  February July May April March Baronial 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() part

Output:

printing the original set ...  {'January', 'February', 'April', 'May', 'June', 'March'}  updating the original set ...  press the modified prepare ...  {'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}          

Removing items from the set up

Python provides the discard() method and remove() method which can be used to remove the items from the gear up. The difference between these role, using discard() part if the item does not exist in the set and so the set remain unchanged whereas remove() method will through an error.

Consider the following example.

Example-i Using discard() method

Output:

printing the original set ...  {'February', 'Jan', 'March', 'April', 'June', 'May'}  Removing some months from the set...  Printing the modified fix... {'February', 'March', 'Apr', 'June'}  looping through the set elements ...  Feb March Apr June          

Python provides besides the remove() method to remove the item from the set up. Consider the following example to remove the items using remove() method.

Example-2 Using remove() part

Output:

printing the original set ...  {'February', 'June', 'April', 'May', 'January', 'March'}  Removing some months from the fix...  Press the modified set... {'February', 'June', 'April', 'March'}          

We can also apply the popular() method to remove the item. By and large, the pop() method will always remove the terminal particular but the prepare is unordered, we can't determine which element will exist popped from fix.

Consider the post-obit example to remove the detail from the prepare using pop() method.

Output:

printing the original ready ...  {'June', 'January', 'May', 'April', 'February', 'March'}  Removing some months from the prepare...  Printing the modified set... {'May', 'April', 'February', 'March'}          

In the higher up code, the final element of the Calendar month set up is March just the pop() method removed the June and Jan because the set is unordered and the pop() method could not decide the terminal chemical element of the prepare.

Python provides the articulate() method to remove all the items from the ready.

Consider the following example.

Output:

press the original set ...  {'January', 'May', 'June', 'Apr', 'March', 'Feb'}  Removing all the items from the set...  Printing the modified set up... set()          

Deviation between discard() and remove()

Despite the fact that discard() and remove() method both perform the same task, There is one main departure between discard() and remove().

If the central to be deleted from the set using discard() doesn't exist in the set, the Python volition not give the fault. The program maintains its control period.

On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the Python volition raise an error.

Consider the post-obit example.

Example-

Output:

printing the original prepare ...  {'March', 'Jan', 'Apr', 'June', 'February', 'May'}  Removing items through discard() method...  printing the modified ready... {'March', 'Jan', 'April', 'June', 'February', 'May'}  Removing items through remove() method... Traceback (virtually recent call terminal):   File "prepare.py", line ix, in      Months.remove("Jan") KeyError: 'January'          

Python Set Operations

Set can be performed mathematical operation such as union, intersection, difference, and symmetric divergence. Python provides the facility to carry out these operations with operators or methods. We describe these operations as follows.

Union of ii Sets

The 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.

Python Set

Consider the post-obit example to summate the union of ii sets.

Example 1: using marriage | operator

Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wed', 'Monday', 'Thursday'}          

Python besides provides the union() method which can as well exist used to calculate the spousal relationship of 2 sets. Consider the following example.

Example 2: using union() method

Output:

{'Friday', 'Mon', 'Tuesday', 'Thursday', 'Wed', 'Sunday', 'Saturday'}          

Intersection of two sets

The intersection of two sets can exist performed by the and & operator or the intersection() function. The intersection of the ii sets is given as the set of the elements that common in both sets.

Python Set

Consider the following example.

Instance 1: Using & operator

Output:

{'Monday', 'Tuesday'}          

Instance 2: Using intersection() method

Output:

{'Martin', 'David'}          

Example 3:

Output:

{i,ii,5}          

The intersection_update() method

The intersection_update() method removes the items from the original set that are non 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 information technology modifies the original ready by removing the unwanted items, on the other hand, the intersection() method returns a new set.

Consider the post-obit example.

Output:

{'castle'}          

Difference betwixt the two sets

The difference of two sets can be calculated past using the subtraction (-) operator or intersection() method. Suppose at that place are ii 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 fix B.

Python Set

Consider the following example.

Instance 1 : Using subtraction ( - ) operator

Output:

{'Thursday', 'Wednesday'}          

Example 2 : Using difference() method

Output:

{'Th', 'Midweek'}          

Symmetric Difference of two sets

The symmetric divergence of two sets is calculated by ^ operator or symmetric_difference() method. Symmetric deviation of sets, information technology removes that element which is present in both sets. Consider the post-obit example:

Python Set

Example - 1: Using ^ operator

Output:

{three, four, 5, 6, 8, 9, ten}          

Case - 2: Using symmetric_difference() method

Output:

{3, 4, 5, 6, viii, ix, x}          

Set comparisons

Python allows u.s. to utilise the comparison operators i.e., <, >, <=, >= , == with the sets by using which nosotros 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 within the sets.

Consider the following example.

Output:

True False Fake          

FrozenSets

The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen ready cannot exist changed and therefore it can be used equally a fundamental in the dictionary.

The elements of the frozen set cannot be changed later on the cosmos. 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 ready as a render blazon of the method.

Consider the following case to create the frozen ready.

Output:

<class 'frozenset'>  printing the content of frozen set... 1 2 iii 4 5 Traceback (most contempo call last):   File "set up.py", line 6, in <module>     Frozenset.add(6) #gives an fault since nosotros tin can change the content of Frozenset afterwards cosmos  AttributeError: 'frozenset' object has no aspect 'add'          

Frozenset for the dictionary

If we pass the dictionary every bit the sequence within the frozenset() method, it will accept merely the keys from the lexicon and returns a frozenset that contains the primal of the dictionary as its elements.

Consider the post-obit instance.

Output:

<class 'dict'> <course 'frozenset'> Name Land ID          

Set Programming Example

Example - one: Write a programme to remove the given number from the set.

Output:

Enter the number you desire to remove:12 After Removing: {i, 2, three, iv, 5, 6, 24}          

Example - 2: Write a plan to add multiple elements to the set.

Output:

{1, 2, 4, 'Apple tree', 'John', 'CS', 'Mango', 'Grapes'}          

Instance - three: Write a program to find the union betwixt two ready.

Output:

{96, 65, 2, 'Joseph', 1, 'Peter', 59}          

Example- four: Write a programme to discover the intersection betwixt two sets.

Output:

{56, 23}          

Instance - 5: Write the plan to add element to the frozenset.

Output:

TypeError: 'frozenset' object does non support item assignment          

Above code raised an error because frozensets are immutable and can't exist changed after creation.

Example - 6: Write the program to find the issuperset, issubset and superset.

Output:

False Imitation Truthful True          

Python Congenital-in fix methods

Python contains the following methods to exist used with the sets.

SN Method Description
1 add together(item) It adds an item to the set. It has no effect if the item is already present in the gear up.
2 clear() It deletes all the items from the set up.
3 copy() It returns a shallow re-create of the set.
4 difference_update(....) It modifies this set by removing all the items that are too present in the specified sets.
5 discard(item) It removes the specified particular from the set.
six intersection() It returns a new gear up that contains only the common elements of both the sets. (all the sets if more than two are specified).
7 intersection_update(....) It removes the items from the original set up that are not present in both the sets (all the sets if more than one are specified).
8 Isdisjoint(....) Render Truthful if two sets have a zilch intersection.
nine Issubset(....) Report whether another set contains this set up.
10 Issuperset(....) Written report whether this gear up contains some other set.
11 pop() Remove and return an arbitrary ready chemical element that is the last chemical element of the ready. Raises KeyError if the fix is empty.
12 remove(item) Remove an element from a set; it must be a fellow member. If the element is not a fellow member, raise a KeyError.
13 symmetric_difference(....) Remove an element from a set; it must exist a member. If the chemical element is non a member, heighten a KeyError.
fourteen symmetric_difference_update(....) Update a prepare with the symmetric divergence of itself and another.
xv union(....) Return the matrimony of sets as a new set.
(i.east. all elements that are in either set up.)
16 update() Update a set with the marriage of itself and others.

Next Topic Python Lexicon

← prev next →

How To Create Set In Python,

Source: https://www.javatpoint.com/python-set

Posted by: jonesseticivere.blogspot.com

0 Response to "How To Create Set In Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel