From the course: Python Data Structures: Sets and Frozen Sets
Video is locked.
Unlock the full course today
Join today to access over 18,300 courses taught by industry experts or purchase this course individually.
Find the sum of all elements in a set
“
- [Instructor] You are provided with a set s1, it has elements 10, 20, 30, 40, 50 in it. Now, how
would you calculate the sum of all the elements present in the set? This can be done in two ways. Now, before we use the built-in method present in Python, first, let us solve the same problem using logic. So what we can do is we can take a variable total and initialize it to zero. And then just iterate over set s1. So for num in s1, we can keep incrementing the value of total. And now after the iteration is complete we can just print the value. Sum of all elements present in set is, total. We
have already written the function so we can remove this statement. Python3, sum.py. Now you can see the result is 210. You can verify it by manually summing all the numbers. Now how you can solve the same problem without using loops, all you need to do is first let us initialize the set. Our values were 10, 20, 30, 40, 50, and 60.…
Contents
How do you print the sum of elements in a set?
Python.
#Initialize array..
arr = [1, 2, 3, 4, 5];.
sum = 0;.
#Loop through the array to calculate sum of elements..
for i in range(0, len(arr)):.
sum = sum + arr[i];.
print("Sum of all the elements of an array: " + str(sum));.
What is sum () in Python?
Python sum() Function
The sum() function returns a number, the sum of all items in an iterable.
How do you sum inputs in Python?
How to Add Two Numbers in Python.
❮ Previous Next ❯.
Example. x = 5. y = 10. print(x + y) Try it Yourself ».
Example. x = input("Type a number: ") y = input("Type another number: ") sum = int(x) + int(y) print("The sum is: ", sum) Try it Yourself ».
❮ Previous Next ❯.
How do you sum elements in a list?
Sum Of Elements In A List Using The sum() Function. Python also provides us with an inbuilt sum() function to calculate the sum of the elements in any collection object. The sum() function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.