In this Python set program, we will find the average of elements in a set with the help of the below-given steps.
What is set?
Sets are used to store multiple items in a single variable.
The set is one of 4 built-in data types in Python used to store collections of data.
It is an unordered collection data type that is iterable, mutable and has no duplicate elements.
Average of elements in a set:
Steps to solve the program
1. Create a set using {}.
2. Add some elements in the set.
3. Create a variable total and assign its value equal to 0.
4. Use a for loop to iterate over elements in the set.
5. During iteration add element to the total variable to get the sum of elements in a set.
6. Now divide the total by length of the set to get the average of elements in a set.
7. Use len() function for this purpose.
8. Print the output.
Set = {1,2,3,4,5}
print("Original set1: ",Set)
total = 0
for ele in Set:
total += ele
print("Average of the set: ",total/len(Set))
Output :
Original set1: {1, 2, 3, 4, 5}
Average of the set: 3.0
Related Articles
Python program to check if all elements in a set are even.
Python program to check if all elements in a set are odd.
Python program to check if all elements in a set are prime.
Python program to check if a set is a proper subset of another set.
Python program to find the cartesian product of two sets.
Python program to find the power set of a set.