In this Python tutorial we will learn about Python Sets and we will also cover different examples related to Python Sets.
Python Set
In Python set is an unordered group of datatype that is mutable and has no duplicate elements. In sets the order of the elements are unspecified and the sets are different to a list
Example:
In the following code, we will creating the set with the use of a string, with the use of constructor and with the use of a list.
# Python program to demonstrate python set
# Creating a Set
setpy = set()
print("Blank Set: ")
print(setpy)
# Creating a Set with the use of a String
setpy = set("Pythontpoint")
print("\n Set with the use of String: ")
print(setpy)
# Creating a Set with the use of Constructor
# Using object to Store String
Strng = 'Pythontpoint'
setpy = set(Strng)
print("\n Set with the use of an Object: " )
print(setpy)
# Creating a Set with the use of a List
setpy = set(["Python", "t", "point"])
print("\n Set with the use of List: ")
print(setpy)
Output:
After running the above code we get the following output in which we can see that the set are created with the use of a string, constructor, and list.
Github Link
Check this code in Repository from Github and you can also fork this code.
Github User Name: PythonT-Point
Creating a Set
In Python the set are created by using the set() function with a sequence and this sequence can be placed inside the curly braces and separated by commas.
Example:
In the following example we are creating the sets by using the set() function with a sequence and the sequence are placed inside the curly braces and separated with commas.
# Creating a Set with a List of Numbers
# Having duplicate values
pyset = set([2, 3, 5, 5, 6, 6, 6, 7, 4])
print("\n Set with the use of Numbers: ")
print(pyset)
# Creating a Set with a mixed type of values
# Having numbers and strings
pyset = set([2, 3, 'Python', 5, 't', 7, 'point'])
print("\n Set with the use of Mixed Values")
print(pyset)
Output: After running the above code we get the following output in which we can see that the set is created.
Read: Python Dictionary
Adding elements to Python Sets
The element can be added in the python set by simply using the add() function. We can add one element at a time by using the add() function. If we want to add multiple element then we can use loop with the add() function.
Example:
In the following set we are adding the elements by simply using the add() function. By adding the add the elements for creating the sets.
# Python program to demonstrate
# Addition of elements in a Set and Creating a Set
pyset = set()
print("Blank Set: ")
print(pyset)
# Adding a element and tuple to the Set
pyset.add(6)
pyset.add(7)
pyset.add((4, 5))
print("\nSet after Addition of three elements: ")
print(pyset)
# Adding elements to the set using iterator
for x in range(2, 5):
pyset.add(x)
print("\n Set after Addition of elements from 2-5: ")
print(pyset)
Output:
In the following output we can see that the elements are added in the set and printed on the screen.
Accessing elements to Python Sets
In python the sets are unordered and the item has no index and not accessed by referring to an index. In set the For loop can be used for loop through the set item.
Example:
In the following code we are accessing the elements in a set and creating a set by using the set() function.
# Python program to accessing of elements in a set
# Creating a set
setpy = set(["Python", "t", "point"])
print("\nInitial set")
print(setpy)
# Accessing element using for loop
print("\nElements of set: ")
for x in setpy:
print(x, end=" ")
# Checking the element using in keyword
print("python" in setpy)
Output:
After running the above code we get the following output in which we can see that the set are created by accessing the elements.
Read: Python Strings
Removing elements from Python Sets
The python the element can be remove from the set by remove() function. If the element does not exist in the set the error should be arise.
Example:
In the following code we are deleting the element in a set by simply using the delete() function and creating a set.
# Python program to demonstrate delete elements in a Set
# Creating a Set
pyset = set([1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(pyset)
# Removing elements from set using remove() method
pyset.remove(6)
pyset.remove(8)
print("\nSet after Removal of two elements: ")
print(pyset)
# Removing elements from set using discard() method
pyset.discard(9)
pyset.discard(10)
print("\nSet after discarding two elements: ")
print(pyset)
# Removing elements from set using iterator method
for x in range(2, 6):
pyset.remove(x)
print("\nSet after Removing a range of elements: ")
print(pyset)
Output:
After running the above code we get the following output in which we can see that the elements are deleted and the set are created.
So, in this tutorial, we have learned about the Python Sets and we have covered all these topics.
- Python Set
- Creating a Set
- Adding elements to Python Sets
- Accessing elements to Python Sets
- Removing elements from Python Sets
Do follow the following tutorials also:
It was impossible for me to leave your website without expressing my gratitude for the excellent knowledge you give your visitors. Without a doubt, I’ll be checking back frequently to see what updates you’ve made.
I would like to thank you for the efforts you have put in writing this website. I am hoping the same high-grade web site post from you in the upcoming also. In fact your creative writing skills has encouraged me to get my own site now. Actually the blogging is spreading its wings fast. Your write up is a great example of it.
Wow amazing blog layout How long have you been blogging for you made blogging look easy The overall look of your web site is magnificent as well as the content
I was just as enthralled by your work as you were. Your sketch is elegant, and your written content is sophisticated. However, you seem concerned about potentially delivering something questionable soon. I’m confident you’ll resolve this issue quickly and return to your usual high standards.
I loved as much as youll receive carried out right here The sketch is tasteful your authored material stylish nonetheless you command get bought an nervousness over that you wish be delivering the following unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike
Temp mail Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
Your article helped me a lot, is there any more related content? Thanks!
Wonderful beat I wish to apprentice while you amend your web site how could i subscribe for a blog web site The account aided me a acceptable deal I had been a little bit acquainted of this your broadcast provided bright clear idea
obviously like your website but you need to test the spelling on quite a few of your posts Several of them are rife with spelling problems and I to find it very troublesome to inform the reality on the other hand Ill certainly come back again
Wonderful web site Lots of useful info here Im sending it to a few friends ans additionally sharing in delicious And obviously thanks to your effort
Somebody essentially lend a hand to make significantly articles Id state That is the very first time I frequented your website page and up to now I surprised with the research you made to make this actual submit amazing Wonderful task
Лучшие онлайн-казино предлагают своим пользователям широкий выбор игр, включая слоты, рулетку, блэкджек, покер и другие. Кроме того, они часто предлагают бонусы и фриспины новым игрокам, что позволяет им начать играть без необходимости вносить депозит. Регистрация в онлайн-казино обычно занимает несколько минут и требует минимальной информации о пользователе. рейтинг топ лушчее xeafxicunc
Somebody essentially lend a hand to make significantly articles Id state That is the very first time I frequented your website page and up to now I surprised with the research you made to make this actual submit amazing Wonderful task
Insanont I really like reading through a post that can make men and women think. Also, thank you for allowing me to comment!
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Hello Neat post Theres an issue together with your site in internet explorer would check this IE still is the marketplace chief and a large element of other folks will leave out your magnificent writing due to this problem
Blue Techker I really like reading through a post that can make men and women think. Also, thank you for allowing me to comment!
Keep up the fantastic work! Kalorifer Sobası odun, kömür, pelet gibi yakıtlarla çalışan ve ısıtma işlevi gören bir soba türüdür. Kalorifer Sobası içindeki yakıtın yanmasıyla oluşan ısıyı doğrudan çevresine yayar ve aynı zamanda suyun ısınmasını sağlar.
FinTech ZoomUs For the reason that the admin of this site is working, no uncertainty very quickly it will be renowned, due to its quality contents.
My brother recommended I might like this web site He was totally right This post actually made my day You cannt imagine just how much time I had spent for this information Thanks
Mountsinai This was beautiful Admin. Thank you for your reflections.
Blue Techker very informative articles or reviews at this time.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.