Questions tagged [sum]

The result of adding two or more quantities together.

The sum or total refers to the result of a summation operation. To refer to the operation yields a sum, use the [tag: addition] tag. A summation involves adding two or more numbers or other quantities. It is primarily an arithmetic operation which means it deals with numbers and also other mathematical objects. However, sum can be used in other contexts which may not necessarily be a result of a mathematical operation. Almost all programming languages support addition of numbers using the + operator. Most programming languages support the summation operation through a built-in language construct or as a utility function part of the standard library.


Examples of sum in various programming languages

C++

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> array{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int sum = std::accumulate(array.begin(), array.end(), 0, std::plus<int>());
    std::cout << sum;
    return 0;
}

Python:

sum_of_items = sum([1, 2, 3, 4, 5, 6])
# sum_of_items will be equal to 21

SQL

SELECT SUM(column1) FROM MyTable
WHERE column1 = "condition"

C#

List<int> array = new List<int>() {1, 2, 3, 4, 5};
int sum = array.Sum();  # sum == 21

Java

import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
      var numbers = Arrays.asList(1, 2, 3, 4, 5);
      var sum = numbers.stream().mapToInt(Integer::intValue).sum();
      System.out.println(sum);
    }
}

R

x <- c(1.1, 2.5, -0.4)
y <- c(NA, 1.7)
sum(x)
sum(y)
sum(y, na.rm = TRUE)
sum(x, y)  ## as same as sum(c(x, y))
sum(x, y, na.rm = TRUE)  ## as same as sum(c(x, y), na.rm = TRUE)
15351 questions
620
votes
16 answers

How to sum array of numbers in Ruby?

I have an array of integers. For example: array = [123,321,12389] Is there any nice way to get the sum of them? I know, that sum = 0 array.each { |a| sum+=a } would work.
brainfck
  • 9,286
  • 7
  • 28
  • 29
444
votes
26 answers

Sum a list of numbers in Python

Given a list of numbers such as: [1, 2, 3, 4, 5, ...] How do I calculate their total sum: 1 + 2 + 3 + 4 + 5 + ... How do I calculate their pairwise averages: [(1+2)/2, (2+3)/2, (3+4)/2, (4+5)/2, ...]
layo
  • 4,489
  • 2
  • 15
  • 3
360
votes
11 answers

How to sum all the values in a dictionary?

Let's say I have a dictionary in which the keys map to integers like: d = {'key1': 1,'key2': 14,'key3': 47} Is there a syntactically minimalistic way to return the sum of the values in d—i.e. 62 in this case?
nedblorf
  • 5,135
  • 4
  • 27
  • 28
220
votes
5 answers

Get total of Pandas column

I have a Pandas data frame, as shown below, with multiple columns and would like to get the total of column, MyColumn. print df X MyColumn Y Z 0 A 84 13.0 69.0 1 …
Enigmatic
  • 3,902
  • 6
  • 26
  • 48
210
votes
8 answers

Pandas: sum DataFrame rows for given columns

I have the following DataFrame: In [1]: df = pd.DataFrame({'a': [1, 2, 3], 'b': [2, 3, 4], 'c': ['dd', 'ee', 'ff'], 'd': [5, 9, 1]}) df Out [1]: a b c d 0 1 2 dd 5 1 2 3 ee 9 2…
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
207
votes
4 answers

C# List of objects, how do I get the sum of a property

I have a list of objects. One property of the individual object entry is amount. How do I get the sum of amount? If my list was of type double I may be able to do something like this: double total = myList.Sum(); However I want to something similar…
Joseph U.
  • 4,457
  • 10
  • 41
  • 47
191
votes
29 answers

How do you find the sum of all the numbers in an array in Java?

I'm having a problem finding the sum of all of the integers in an array in Java. I cannot find any useful method in the Math class for this.
TomLisankie
  • 3,785
  • 7
  • 28
  • 32
184
votes
4 answers

How do I get SUM function in MySQL to return '0' if no values are found?

Say I have a simple function in MySQL: SELECT SUM(Column_1) FROM Table WHERE Column_2 = 'Test' If no entries in Column_2 contain the text 'Test' then this function returns NULL, while I would like it to return 0. I'm aware that a similar question…
Nick
  • 4,304
  • 15
  • 69
  • 108
180
votes
23 answers

Add SUM of values of two LISTS into new LIST

I have the following two lists: first = [1,2,3,4,5] second = [6,7,8,9,10] Now I want to add the items from both of these lists into a new list. output should be third = [7,9,11,13,15]
Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71
147
votes
7 answers

Django: Calculate the Sum of the column values through query

I have a model: class ItemPrice(models.Model): price = models.DecimalField(max_digits=8, decimal_places=2) # ... I tried this to calculate the sum of price in this queryset: items = ItemPrice.objects.all().annotate(Sum('price')) What's…
Ahsan
  • 11,516
  • 12
  • 52
  • 79
145
votes
18 answers

How to sum all column values in multi-dimensional array?

How can I add all the columnar values by associative key? Note that key sets are dynamic. Input array: Array ( [0] => Array ( [gozhi] => 2 [uzorong] => 1 [ngangla] => 4 [langthel] => 5 …
marknt15
  • 5,047
  • 14
  • 59
  • 67
132
votes
25 answers

How to find the cumulative sum of numbers in a list?

time_interval = [4, 6, 12] I want to sum up the numbers like [4, 4+6, 4+6+12] in order to get the list t = [4, 10, 22]. I tried the following: t1 = time_interval[0] t2 = time_interval[1] + t1 t3 = time_interval[2] + t2 print(t1, t2, t3) # -> 4 10…
user2259323
  • 1,339
  • 2
  • 9
  • 3
112
votes
4 answers

Sum / Average an attribute of a list of objects

Lets say I have class C which has attribute a. What is the best way to get the sum of a from a list of C in Python? I've tried the following code, but I know that's not the right way to do it: for c in c_list: total += c.a
jsj
  • 9,019
  • 17
  • 58
  • 103
106
votes
11 answers

Sum the digits of a number

If I want to find the sum of the digits of a number, i.e.: Input: 932 Output: 14, which is (9 + 3 + 2) What is the fastest way of doing this? I instinctively did: sum(int(digit) for digit in str(number)) and I found this online: sum(map(int,…
SpFW
  • 1,099
  • 2
  • 8
  • 5
102
votes
6 answers

Pandas: sum up multiple columns into one column without last column

If I have a dataframe similar to this one Apples Bananas Grapes Kiwis 2 3 nan 1 1 3 7 nan nan nan 2 3 I would like to add a column like this Apples Bananas Grapes Kiwis Fruit…
Tuutsrednas
  • 1,337
  • 2
  • 12
  • 14
1
2 3
99 100