In this post
we are going to learn about sets in Python.
What is a
set ?
A set is an
unordered collection of elements with no duplicate elements.
Where are
sets used ?
Basic uses
of sets include :
- Membership testing
- Elimination
of duplicate entries.
Set
operations also support mathematical operations such as union, intersection, difference
and symmetric difference.
How to use
sets ?
Sets can be
implemented using curly braces {} or using the set() method.
For instance, set = {2,5,6}
Note :
How do you
create an empty set ?
We must use
set() function to create an empty set. Declaring a set with empty braces will
not work.
If you use
{} braces, then you are not creating an empty set but a dictionary.
Examples :
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been
removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>> # Demonstrate set operations on
unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in either a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Similar to
list comprehensions there are set comprehensions too.
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
Task on Sets :
Now, let's use our knowledge of sets and help Mickey.
Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.
169.375
Solution :
n = int(input()) # read the input from the standard input
l = input()
li = l.split(" ")
mList = list(map(int,li)) # converting the list of strings into integers
sets = set(mList) # creating a set
modified_list = list(sets) # convert the set into list to access the items
sum = 0
for i in modified_list:
sum = sum + i
print(sum/len(sets)) # printing the average