Sets • Set isanother data structure supported by Python. • It is Mutable. • It is unordered. • Does not have the concept of indexing. • No meaning of duplicate elements. • Symbol used for representing set is { } For example, s={1,2,3}
3.
Q1. How wecan create empty set in Python? ANS. S=set() S={} will not create empty set. It will create empty dictionary.
4.
Sets are Mutable Wecan add elements in set by using following methods:- 1. s.add(element):- This will add one element at a time in the set s s={1,2,3} s.add(10) print(s) O/P:- {1,2,3,10} Elements may be in any order
5.
2. s1.update(s2):- Thiswill add one or more than one element at a time in a set. s1={1,2,3} s2={88,67} # or s2=[88,67] or s2=(88,67) s1.update(s2) print(s1) O/P:- {1,2,3,88,67} Elements may be in any order
6.
For deletion, weare having different methods:- 1. s.pop():- This will delete arbitrary element from the given set s s={4,5,6} s.pop() print(s) O/P: -{4,6} or {4,5} or {5,6} 2. s.remove(element):- This will delete the specified element. s={4,5,6} s.remove(4) print(s) O/P:- {5,6}
7.
3. s.discard(element):- Itis similar to remove method. The difference lies when the specified element is not present in the set. s.discard(element) does not raises an error when element is not there while s.remove(element) raises an error s={1,2,3} s.discard(4) print(s) O/P:- {1,2,3}
8.
4. s.clear():- Thiswill empties the set s={1,2,3} s.clear() print(s) O/P:- set()
Functions for sets max(s) min(s) sum(s) sorted(s)- It will return a list of sorted elements
12.
What is s1? S1=set(“My name is Piyush and Piyush is My name”.split()) print(S1) ANS. {“My”, ”name”, ”is”, ”Piyush”, ”and”}
13.
The elementsof sets must be immutable but set itself is mutable. s1={1,2,3,4} Right s2={1,2,3,(4,5)} Right s3={1,2,3,[4,5]} Wrong s4={1,2,3,”Hello”} Right
14.
Is there anyerror? 1. s={10,45,63,56} print(s[0]) 2. s={10,45,63,56} s[1]=500 3. s={4,5,[100,200]} print(s) 4. s={1,2,3,4} print(s[0:2])
Programs 1. Write aProgram that generates a set s1 of 10 even numbers and another set s2, of 10 odd numbers 2. Write a Program that generates a set s1 of prime numbers from 100 to 999 and another set s2, of Armstrong numbers from 100 to 999. 3. Do the operation of union, intersection, difference, symmetric difference of sets s1 and s2(refer Program 1)
17.
4.Do the operationof union, intersection, difference, symmetric difference of sets s1 and s2(refer Program 2) 5. Write a Program that creates two sets(s1 and s2) that stores squares and cubes of numbers from 1 to 10 respectively. Now Demonstrate the use of update(), pop(), remove(), add() and clear()
18.
6. Write aProgram that creates two sets. One of even numbers in range 1-10 and other has all composite numbers in range 1-20. Demonstrate use of issuperset(), len() and sum() functions on the sets. 7. Write a Program that has a list of countries. Create a set of the countries and print the names of the countries in sorted order.