Sets are basically a collection of specific items that are unordered. There is no particular order in which they are stored. In Python, the sentences are the same, but there are few differences from the basic sentences.
- The elements in Python sets are unique, there can be no duplicate elements in Python sets. If duplicate items are entered, they are ignored and the final set always contains unique items.
- Python sets are mutable. But its elements are immutable. Items once entered cannot be changed.
- The member of the Python set cannot be accessed through indexes. Set elements do not have an associated index.
This tutorial explains the following examples in Python set:
- Create a simple sentence
- Build a set with Constructor
- Create an empty set
- Create set from list
- Create a set of tuples
- Access a specific stat in the set
- Adding elements to a set - using the Add method
- Adding elements to a set - using the update method
- Remove elements from the set - using the discard method
- Remove items from the set - Using the remove method
- Union operation on sets
- Hybrid operation on sets
- Difference operation on sets
- Symmetric difference of two sets
- Compare two sentences
- Membership Test on Sets
- iteration on set
- Delete a sentence
- Solved an interesting problem with sets
- Complete sample code from Sets - sets.py
1. Create a simple sentence
Python sets can be created by simply enclosing the elements in curly braces.
>>> primes={3,5,7,9,11,13}>>> type(primes)<class 'set'>
Note: Remember that Python dictionaries also use {} in the declaration. But in the example above, we created a set as indicated by the output of the type command.
Information about Python dictionaries can be found here:Python dictionary examples - create, update and delete items
2. Create a set with constructor
Use set as shown below, passing the initial string as a constructor.
In the following example, we intentionally add another "s" before "stuff" that is ignored by the set. Only one "s" is needed even if we specified more than one.
>>> unique=set("thegeeksstuff");>>> unique{'h', 't', 'u', 's', 'f', 'e', 'g', 'k'}> >> type(eindeutig)<class 'set'>
3. Create an empty set
The following is an incorrect method of creating an empty set. This creates an empty dictionary:
>>> empty={}>>> type(leer)<class 'dict'>
The correct procedure to create is shown below. To create an empty set, use the set method with an empty constructor, as shown below.
>>> empty=set();>>> type(leer)<class 'set'>
When trying to create an empty set, use the constructor method. Otherwise, the first method creates an empty dictionary instead.
4. Create a sentence from the list
First, create a list as shown below:
>>> primesList=[3,5,7,11,13,17];
More information about the list can be found here:Python list examples - insert, append, length, index, remove, pop
Next, create a set using the list above:
>>> primeSet=set(primesList)>>> type(primeSet)<class 'set'>>>> primeSet{3, 5, 7, 11, 13, 17}
5. Create a set of tuples
First, create a tuple as shown below.
>>> p=(3,5,7,11,13);>>> p(3, 5, 7, 11, 13)>>> type(p)<class 'tuple'>
More information about tuples can be found here:17 practical examples of Python tuples
Next, create a Set from the tuple above:
>>> primes=set(p);>>> p(3, 5, 7, 11, 13)>>> type(primes)<class 'set'>>>> primes{3, 5, 7, 11 , 13}
6. Access a specific value in Set
Set items are not specifically accessible, no index is attached. We cannot access elements of sets.
>>> primes = {3, 5, 7, 11, 13}>>> primes[1]Traceback (last call last): file "<pyshell#21>", line 1, in <module>primes[1 ] TypeError: 'set' object does not support indexing
7. Adding elements to a set - using the Add method
Items can be added to the set using two methods, add and update. The Add method can insert a single item, but the Update method can also insert tuples and lists.
>>> primes={3,5,7,11};>>> primes{11, 3, 5, 7}>>> primes.add(19);>>> primes{3, 5, 7, 11 , 19}
8. Adding Elements to a Set - Using the Update Method
In the following, the elements from the plist are added to the primes set.
>>> plist=[12,14,15,16];>>> primes.update(plist);>>> primes{3, 5, 7, 11, 12, 14, 15, 16, 19}
9. Remove elements from the set - using the discard method
Items can be removed from the set using the Discard and Remove methods. When removing items, if an item is not there, you remove reports and errors, while discarding does not.
>>> primes{3, 5, 'santosh', 7, 11, 12, 14, 15, 16, 19}>>> primes.discard("santosh")>>> primes{3, 5, 7, 11 , 12, 14, 15, 16, 19}>>> primes.discard("santosh");
Discard does not report an error when attempting to remove items that have already been removed.
10. Remove items from the set - Use the remove method
Currently primes set has the following values.
>>> prime numbers{3, 5, 7, 11, 12, 14, 15, 16, 19}
In the following, the element with value 11 is removed from the primes set.
>>> primes.remove(11);
As you can see below, we no longer see a value 11 item in the prime set.
>>> primes{3, 5, 7, 12, 14, 15, 16, 19}>>> primes.remove(11);Traceback (last call last):File "<pyshell#23>", line 1 , in <module>primes.remove(11);KeyError: 11
Remove method reported an error when attempting to remove a non-existent item.
11. Union Operation on Sets
The union operation (|) creates a new set with different elements from both sets.
>>> prime1={3,5,7,11};>>> prime2={3,5,7,11,13,17,19}>>> primes=prime1 | prime2>>> primes{3, 5, 7, 11, 13, 17, 19}
12. Cutting operation on sets
The intersection operation (&) creates a new set with elements common to both sets.
>>> prime1={3,5,7,11};>>> prime2={3,5,7,11,13,17,19}>>> primes=prime1 & prime2>>> primes{3, 11, 5, 7}
13. Difference operation on sets
The difference operation creates a new set that contains elements that are in the first set but not in the second set
>>> prime2={3,5,7,11,13,17,19}>>> prime1={3,5,7,11};>>> primes=prime2-prime1>>> primes{17, 19, 13}
14. Symmetrical difference of two sets
The symmetric difference of two sets creates a new set that contains elements from both sets except common elements.
>>> prime2={3,5,7,11,13,17,19}>>> prime1={3,5,7,11,91,101};>>> primes=prime2 ^ prime1>>> primes{ 17, 19, 101, 91, 13}
15. Compare two sentences
Using comparison, we can check whether a set is a superset, a subset, or equal to another set.
>>> prime1={3,5,7,11,91,101};>>> prime={3,5,7,11,91,101};>>> test=prime==prime1>>> testTrue>>> prime1={3,5,7,11,91,101};>>> prime2={3,5,7,11,13,17,19}>>> test=prime2<prime1>>> testFalse>>> prime2 ={3,5,7,11,13,17,19}>>> prime1={3,5,7,11,91,101};>>> prime1={3,5,7,11};>> > test=prime2<prime1>>> testFalse>>> test=prime2>prime1>>> testTrue
16. Membership Test on Sets
We can test whether an item is present in the specified quantity or not.
>>> prime1={3,5,7,11,91,101};>>> test= 3 in prime1>>> testTrue>>> test=13 in prime1>>> testFalse
17th iteration on set
For this example, let's use the following set of prime numbers.
>>> primes={3,5,7,11,91,101};use the for loop to iterate over the set elements.>>> for prime in primes:print(prime);35101711
More information about the for loop can be found here:12 examples of basic Python for loop commands
18. Delete a sentence
The delete method can be used to delete all elements of the set.
>>> prime1{3, 5, 101, 7, 11, 91}>>> prime1.clear()>>> prime1set()
19. Fixed an interesting problem with sets
Problem: Given a list of integers, print out all distinct elements.
With Sets we can solve this problem in a single line of code.
>>> Number = [1,2,3,4,5,2,3,4,7,8,9,8,12,13,14,14,19]>>> Number[1, 2, 3 , 4, 5, 2, 3, 4, 7, 8, 9, 8, 12, 13, 14, 14, 19]>>> print (set(number)){1, 2, 3, 4, 5, 7, 8, 9, 12, 13, 14, 19}
This was one use case, similarly sets can be useful in other scenarios.
20. Complete Sample Code of Sets – sets.py
Create a sets.py file
vi sets.py
Copy and paste the following into sets.py and run it for testing purposes.
#1) create setprimes={3,5,7,9,11,13}type(primes)# 2) create set with constructorunique=set("thegeeksstuff");unique# 3) create empty setempty={ }type( empty)empty=set();type(empty)#4) Create set from listprimesList=[3,5,7,11,13,17];primeSet=set(primesList)type(primeSet)primeSet# 5 ) create set from tuplep=(3,5,7,11,13);primes=set(p);type(primes)primes# 6) access values in SetPrimes = {3, 5, 7, 11, 13} ;#Primes[ 1]; # Comment out this throwing error#7) Using Add methodprimes={3,5,7,11};primes.add(19);primes#8) Using update methodplist=[12,14,15,16];primes. update (plist);primes#9) using discardprimes={3, 5, 'santosh', 7, 11, 12, 14, 15, 16, 19};primes.discard("santosh")# 10) using removeprimes = { 3, 5, 7, 11, 12, 14, 15, 16, 19}primes.remove(11);primes;#11) Union operation on setsprime1={3,5,7,11};prime2 ={3, 5,7,11,13,17,19}primes=prime1 | prime2primes# 12) intersection operation on setsprime1={3,5,7,11};prime2={3,5,7,11,13,17,19}primes=prime1 & prime2primes# 13) difference operation on setsprime2={ 3, 5,7,11,13,17,19}Prime1={3,5,7,11};Prime=Prime2-Prime1Prime# 14) Symmetric differencePrime2={3,5,7,11,13,17,19} prime1={3,5,7,11,91,101};primes=prime2 ^ prime1primes# 15) Compare two sets prime1={3,5,7,11,91,101};prime={3,5,7,11 ,91,101 };test=prime==prime1testprime1={3,5,7,11,91,101};prime1={3,5,7,11};test=prime2<prime1test#16) membership test on setsprime1={3 ,5, 7,11,91,101};test= 3 in prime1test# 17) Iteration on setprimes={3,5,7,11,91,101};for prime in primes: print(prime);# 18) Delete a setprime1 {3, 5, 101, 7, 11, 91}prime1.clear()#19) interesting problem number = [1,2,3,4,5,2,3,4,7,8,9,8,12 ,13, 14,14,19] print (set(number))
Running the sets.py above will result in the following output. Study the above code carefully to understand why you are getting the following output.
$ python sets.py3571191101set([1, 2, 3, 4, 5, 7, 8, 9, 12, 13, 14, 19])