banner



How To Access Elements In Set Python

Python Set up is a programmatic form of sets in mathematics and one of the core data structures in Python. Information technology is an unordered and unique collection of immutable objects. But it is in itself mutable by default.

In this class, yous'll discover – what is a Python set up and what are its properties. You lot'll acquire how to create a set up object, add together and remove elements in it.

Moreover, the tutorial as well provides examples to understands the different operations such as Union, Intersection, Difference, and Symmetric difference.

Python Fix – Acquire Stride by Stride

Contents

  • 1 Sets in Python
    • 1.1 What is a Gear up?
    • one.2 Properties of a Set
  • 2 Create or Update Python Fix
    • 2.ane Create a Fix
    • 2.2 Add together Elements to a Gear up
  • 3 Remove Elements from a Gear up
  • 4 Python Set Operations
    • iv.1 Spousal relationship Operation
    • 4.2 Intersection Operation
    • four.3 Difference Operation
    • 4.4 Symmetric Deviation
  • v Miscellaneous Set Operations
    • 5.i Access Set Elements
    • five.two Set Membership Test
  • half-dozen Frozen Sets in Python
  • 7 Summary

Sets in Python

What is a Set?

Set is a term that originates from Mathematics. Simply, in Python, it is a collection type object which can store elements of different data types. It doesn't index the values in a particular order.

Properties of a Set

A Python ready has the post-obit characteristics.

  • The elements don't have a specific order, and their positions can be inconsistent.
  • Each particular is unique in a Set up and, therefore, tin can't accept duplicates.
  • The elements are immutable and hence, can't accept changes once added.
  • A set is itself mutable and allows the addition or deletion of items.

With Sets, nosotros tin can execute several mathematical operations such as Union, Intersection, Symmetric Divergence, and Complement.

Create or Update Python Set

Create a Set

Yous can invoke any of the following two methods to create a Python Set.

  1. If you have a fixed set of elements, and then grouping them using a comma as the separator and enclose the group within curly braces.
  2. Another way is to telephone call the built-in "set()" method, which tin can also be used to add together elements at run-time.

Also, call back, the elements can be of any data types such as an integer, float, tuple, or string, etc. The only exception with a set is that information technology can't store a mutable item such as List, Set, or Dictionary.

# create a set up of numbers py_set_num = {3, 7, eleven, xv} impress(py_set_num)  # create a set of mixed data types py_set_mix = {xi, 1.ane, "11", (1, 2)} print(py_set_mix)

Executing the higher up lawmaking will return the post-obit output.

# output {three, eleven, seven, 15} {(1, 2), 1.1, 11, '11'}

Follow one more example of Python Fix to gain more than clarity.

# set can't store duplicate elements py_set_num = {three, seven, 11, 15, 3, 7} # it'll automatically filter the duplicates print(py_set_num)  # create a fix using the prepare() method # creating set with a fixed ready of elements py_set_mix = set([11, one.1, "11", (1, 2)]) impress(py_set_mix)  # creating set up with dynamic elements py_list = [11, 1.i, "xi", (1, 2)] py_list.suspend(12) impress(py_list) py_set_mix = set(py_list) print(py_set_mix)

Check out the result of the above code later on execution.

# output {11, 3, fifteen, seven} {(1, ii), 1.1, 11, '11'} [11, one.one, '11', (one, 2), 12] {(one, 2), 1.1, eleven, 'xi', 12}

Let'southward now do one more test with sets. We'll no effort to create an empty Python Set.

# Allow's effort to create an empty Python set py_set_num = {} print("The value of py_set_num:", py_set_num) print("The type of py_set_num:", type(py_set_num))  py_set_num = set() impress("The value of py_set_num:", py_set_num) print("The type of py_set_num:", blazon(py_set_num))

Here is the explanation of the higher up code.

The starting time statement would result in the creation of a dictionary object instead of creating a fix. Yous can't merely use curly braces and look a "Set" in return.

While in the next non-print statement, we used the set() function but didn't pass whatever argument to information technology. Information technology will somewhen return us an empty Set object.

Please refer to the beneath output of the last example.

# output The value of py_set_num: {} The blazon of py_set_num: <class 'dict'> The value of py_set_num: prepare() The type of py_set_num: <class 'set'>

Add together Elements to a Set

Python Set is a mutable object. However, it doesn't employ whatever indexing, and hence, it doesn't have any society.

It likewise means that you can't change its elements by accessing through an alphabetize or via slicing.

Withal, there are Set methods similar the add(), which adds a single chemical element and the update(), which can add more than one item.

The update() method can even have tuples, lists, strings, or other sets as an argument. All the same, duplicate elements will automatically get excluded.

# Allow'south try to change a Python set py_set_num = {77, 88}  try:     print(py_set_num[0]) except Exception as ex:     impress("Fault in py_set_num[0]:", ex)  print("The value of py_set_num:", py_set_num)  # Let'southward add an element to the set py_set_num.add together(99) impress("The value of py_set_num:", py_set_num)  # Let's add multiple elements to the gear up py_set_num.update([44, 55, 66]) impress("The value of py_set_num:", py_set_num)  # Let's add a list and a set as elements py_set_num.update([4.4, 5.v, 6.6], {2.2, 4.4, 6.6}) print("The value of py_set_num:", py_set_num)        

In the above example, the get-go line is demonstrating that a set doesn't allow indexing. Nosotros've kept that code inside the effort-except block and then that we tin grab the error, print information technology, and continue with the residue of the execution.

In the next section of the instance, you can see the Ready'south add() and update() methods in action.

Now, bank check out the output of the above Python Gear up example.

# output Error in py_set_num[0]: 'set' object does not back up indexing The value of py_set_num: {88, 77} The value of py_set_num: {88, 99, 77} The value of py_set_num: {66, 99, 44, 77, 55, 88} The value of py_set_num: {66, 99, 4.iv, 5.5, 6.6, 2.2, 44, 77, 55, 88}

Remove Elements from a Set

Y'all tin can use the post-obit Set methods to delete elements from it.

  1. Discard() method
  2. Remove() method

In that location is a small difference in the manner these two methods operate. The discard() method doesn't throw any error if the target item is not the part of the set.

On the contrary, the remove() method will throw the "KeyError" error in such a case.

Follow the beneath example to become more clarity.

# Let's endeavour to use a Python set up py_set_num = {22, 33, 55, 77, 99}  # discard an chemical element from the set py_set_num.discard(99) print("py_set_num.discard(99):", py_set_num)  # remove an chemical element from the set py_set_num.remove(77) print("py_set_num.remove(77):", py_set_num)  # discard an chemical element not nowadays in the set py_set_num.discard(44) impress("py_set_num.discard(44):", py_set_num)  # remove an element not nowadays in the ready endeavor:     py_set_num.remove(44) except Exception equally ex:     print("py_set_num.remove(44) => KeyError:", ex)

It'll generate the following result.

# output py_set_num.discard(99): {33, 77, 22, 55} py_set_num.remove(77): {33, 22, 55} py_set_num.discard(44): {33, 22, 55} py_set_num.remove(44) => KeyError: 44

Autonomously from the methods you've then far seen, there is a pop() method to remove an chemical element.

Besides, since the Ready doesn't utilize indexing, so you tin can't be certain which of the item would get popped. It'll randomly choice one chemical element and remove it.

In that location is also a method called clear(), which flushes everything from the set.

# Let's use the post-obit Python set py_set_num = {22, 33, 55, 77, 99} impress("py_set_num:", py_set_num)  # popular an element from the set py_set_num.popular() print("py_set_num.pop():", py_set_num)  # pop one more chemical element from the set py_set_num.pop() print("py_set_num.pop():", py_set_num)  # clear all elements from the gear up py_set_num.articulate() impress("py_set_num.clear():", py_set_num)

The higher up example will produce the following upshot.

# output py_set_num: {33, 99, 77, 22, 55} py_set_num.pop(): {99, 77, 22, 55} py_set_num.pop(): {77, 22, 55} py_set_num.clear(): set()

Python Set Operations

Like in mathematics, the set supports operations similar union, intersection, difference, and complement so does it in Python.

There are methods as well equally operators available to perform the set operations.

For the illustration purpose, we volition use the following two sets in the next examples.

# We'll use the setA and setB for our analogy setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'} setB = {'a', 'eastward', 'z', 'b', 't', 'o', 'u'}

Wedlock Operation

Spousal relationship of setA and setB is a new gear up combining all the elements from both the Sets.

Python Set - Union
Python Set – Union

The "|" operator is the one to perform the union performance on the sets.

# We'll utilise the setA and setB for our illustration setA = {'a', 'east', 'i', 'o', 'u', 'g', 'h'} setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}  print("Initial setA:", setA, "size:", len(setA)) print("Initial setB:", setB, "size:", len(setB))  print("(setA | setB):", setA | setB, "size:", len(setA | setB))

We've used the Len() method to calculate the length of the set. The output of the above example is as follows:

# output Initial setA: {'u', 'i', 'g', 'o', 'due east', 'h', 'a'} size: vii Initial setB: {'u', 'z', 'b', 'o', 'e', 'a', 't'} size: 7 (setA | setB): {'h', 'u', 'z', 'b', 't', 'k', 'o', 'east', 'i', 'a'} size: 10

You can too achieve similar results using the union() method.

# Python prepare example using the union() method setA = {'a', 'e', 'i', 'o', 'u', 'm', 'h'} setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}  print("setA.wedlock(setB):", setA.wedlock(setB), "size:", len(setA.matrimony(setB))) print("setB.union(setA):", setB.union(setA), "size:", len(setB.union(setA)))

You can apply the wedlock() method on whatever of the set (i.due east., set A or B); the output will remain the same.

# output setA.union(setB): {'a', 'o', 'e', 'b', 'u', 't', 'i', 'g', 'z', 'h'} size: ten setB.wedlock(setA): {'a', 'o', 'e', 'b', 'u', 't', 'i', 'one thousand', 'z', 'h'} size: x

Intersection Operation

The intersection of setA and setB will produce a set comprising mutual elements in both the Sets.

Python Set - Intersection
Python Set – Intersection

You can use Python'southward "&" operator to perform this functioning.

# Python intersection instance using the & operator setA = {'a', 'e', 'i', 'o', 'u', '1000', 'h'} setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}  print("Initial setA:", setA, "size:", len(setA)) print("Initial setB:", setB, "size:", len(setB))  impress("(setA & setB):", setA & setB, "size:", len(setA & setB))

This example will produce the following effect.

# output Initial setA: {'eastward', 'o', 'h', 'a', 'g', 'u', 'i'} size: 7 Initial setB: {'b', 'e', 't', 'o', 'z', 'a', 'u'} size: vii (setA & setB): {'o', 'a', 'u', 'e'} size: 4

Alternatively, you lot can phone call the intersection() method to perform this performance.

# Python set example using the intersection() method setA = {'a', 'e', 'i', 'o', 'u', 'yard', 'h'} setB = {'a', 'eastward', 'z', 'b', 't', 'o', 'u'}  intersectAB = setA.intersection(setB) print("setA.intersection(setB):", intersectAB, "size:", len(intersectAB)) intersectBA = setB.intersection(setA) print("setB.intersection(setA):", intersectBA, "size:", len(intersectBA))

This example will produce the following effect.

# output setA.intersection(setB): {'a', 'u', 'e', 'o'} size: 4 setB.intersection(setA): {'a', 'u', 'e', 'o'} size: iv

Difference Operation

When you perform the deviation operation on two Sets, i.e., <setA – setB>,  the resultant will be a set up of elements that be in the left only not in the correct object.

Python Set - Difference
Python Set – Difference

Likewise, the operation <setB – setA> volition render those elements of setB which don't exist in the setA.

You can utilise the minus (-) operator to carry out this operation.

# Python gear up's difference functioning setA = {'a', 'e', 'i', 'o', 'u', 'k', 'h'} setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}  diffAB = setA - setB print("diffAB:", diffAB, "size:", len(diffAB)) diffBA = setB - setA print("diffBA:", diffBA, "size:", len(diffBA))

There are iii unique elements in both of our input sets that don't exist in another. Check the output below.

# output diffAB: {'i', 'chiliad', 'h'} size: 3 diffBA: {'z', 'b', 't'} size: 3

The next case will demonstrate the aforementioned set of operations using the departure() method.

# Python set'southward departure performance using the difference() method setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'} setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}  diffAB = setA.difference(setB) print("diffAB:", diffAB, "size:", len(diffAB)) diffBA = setB.divergence(setA) print("diffBA:", diffBA, "size:", len(diffBA))

The execution of the above example would produce the below output.

# output diffAB: {'i', 'g', 'h'} size: three diffBA: {'b', 't', 'z'} size: 3

Symmetric Difference

The symmetric difference of two sets volition generate a set of elements that exist in <setA> and <setB> but not in both.

Python Set - Symmetric Difference
Python Ready – Symmetric Deviation

Yous can execute this operation with the aid of the caret operator (^) in Python.

# Python set up example using the caret ^ operator setA = {'a', 'e', 'i', 'o', 'u', 'g', 'h'} setB = {'a', 'e', 'z', 'b', 't', 'o', 'u'}  symdiffAB = setA^setB print("symdiffAB:", symdiffAB, "size:", len(symdiffAB)) symdiffBA = setB^setA print("symdiffBA:", symdiffBA, "size:", len(symdiffBA))

The output is as follows.

symdiffAB: {'z', 't', 'h', 'thousand', 'b', 'i'} size: 6 symdiffBA: {'z', 'h', 'thousand', 't', 'b', 'i'} size: six

Yous can as well become the operation done with the method symmetric_difference().

# Python set example using the symmetric_difference() method setA = {'a', 'e', 'i', 'o', 'u', 'm', 'h'} setB = {'a', 'due east', 'z', 'b', 't', 'o', 'u'}  symdiffAB = setA.symmetric_difference(setB) print("symdiffAB:", symdiffAB, "size:", len(symdiffAB)) symdiffBA = setB.symmetric_difference(setA) print("symdiffBA:", symdiffBA, "size:", len(symdiffBA))

The result is equally follows.

# result symdiffAB: {'z', 'h', 'i', 'g', 't', 'b'} size: half-dozen symdiffBA: {'z', 'i', 'g', 'b', 't', 'h'} size: six

Miscellaneous Set Operations

Admission Set Elements

Information technology'southward non possible to admission an chemical element directly in a set. But you can fetch all of them together. You need a loop to remember a list of particular items over the Set up.

# Python fix case to access elements from a set up handbasket = set(["apple", "mango", "banana", "grapes", "orange"])   for fruit in basket:     print(fruit)

Afterwards executing the above lawmaking, yous'll come across the following output.

# output apple banana mango orange grapes

Set Membership Exam

Y'all tin can surely check if a set contains a particular element or non. You lot tin brand use of the "in" keyword for this purpose.

# Python set example to test elements in a set basket = fix(["apple tree", "mango", "banana", "grapes", "orange"])  # confirm if 'apple' is in the basket impress("Is 'apple' in the basket?", 'apple' in basket)  # confirm if 'grapes' is in the handbasket impress("Is 'watermelon' in the basket?", 'watermelon' in basket)

After executing the in a higher place lawmaking, y'all'll see the following output.

# output Is 'apple' in the handbasket? Truthful Is 'watermelon' in the handbasket? False

Frozen Sets in Python

It is a unique type of set which is immutable and doesn't allow changing its elements after assignment.

It supports all methods and operators as a ready does, but those that don't modify its content.

Every bit you now know that the sets are mutable and thus become unhashable. So, we tin't apply them every bit keys for a Python dictionary. On the reverse, the Frozen Fix is past default hashable and can work as keys to a dictionary.

You tin create a Frozen set with the help of the following function.

frozenset()

Too, the following Python methods can work with the Frozen set.

copy() difference() intersection() isdisjoint() issubset() issuperset() symmetric_difference() union()

The methods which perform add together or remove operations aren't applicable for Frozen sets as they are immutable.

The below sample exhibits the differences between a standard vs. the frozen set.

# Python Sample - Standard vs. Frozen Set  # A standard set std_set = set(["apple", "mango","orange"])   # Adding an element to normal set is fine std_set.add("banana")   print("Standard Ready:", std_set)   # A frozen set frozen_set = frozenset(["apple tree", "mango","orange"])   print("Frozen Set:", frozen_set)   # Beneath lawmaking will raise an error as we are modifying a frozen set try:     frozen_set.add together("banana") except Exception every bit ex:     print("Error:", ex)

Summary

Nosotros hope that later on wrapping upwardly this tutorial, you should feel comfortable in using the Python gear up. However, you may practice more with examples to gain confidence.

Also, to acquire Python from scratch to depth, practise read our step past step Python tutorial . Besides, yous may connect to our social media (Facebook/Twitter) accounts to receive timely updates.

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

0 Response to "How To Access Elements In Set Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel