Python sum of tuple list

I have a list of tuples [always pairs] like this:

[[0, 1], [2, 3], [5, 7], [2, 1]]

I'd like to find the sum of the first items in each pair, i.e.:

0 + 2 + 5 + 2

How can I do this in Python? At the moment I'm iterating through the list:

sum = 0
for pair in list_of_pairs:
   sum += pair[0]

I have a feeling there must be a more Pythonic way.

gsamaras

70.3k41 gold badges180 silver badges283 bronze badges

asked Mar 12, 2009 at 10:37

1

In modern versions of Python I'd suggest what SilentGhost posted [repeating here for clarity]:

sum[i for i, j in list_of_pairs]

In an earlier version of this answer I had suggested this, which was necessary because SilentGhost's version didn't work in the version of Python [2.3] that was current at the time:

sum[[pair[0] for pair in list_of_pairs]]

Now that version of Python is beyond obsolete, and SilentGhost's code works in all currently-maintained versions of Python, so there's no longer any reason to recommend the version I had originally posted.

answered Mar 12, 2009 at 10:39

David ZDavid Z

124k26 gold badges249 silver badges275 bronze badges

0

sum[i for i, j in list_of_pairs]

will do too.

answered Mar 12, 2009 at 10:43

SilentGhostSilentGhost

293k64 gold badges301 silver badges291 bronze badges

6

I recommend:

sum[i for i, _ in list_of_pairs]

Note:

Using the variable _[or __ to avoid confliction with the alias of gettext] instead of j has at least two benefits:

  1. _[which stands for placeholder] has better readability
  2. pylint won't complain: "Unused variable 'j'"

answered Apr 21, 2012 at 3:24

Hui ZhengHui Zheng

9,8242 gold badges34 silver badges40 bronze badges

If you have a very large list or a generator that produces a large number of pairs you might want to use a generator based approach. For fun I use itemgetter[] and imap[], too. A simple generator based approach might be enough, though.

import operator
import itertools

idx0 = operator.itemgetter[0]
list_of_pairs = [[0, 1], [2, 3], [5, 7], [2, 1]]
sum[itertools.imap[idx0, list_of_pairs]]

Note that itertools.imap[] is available in Python >= 2.3. So you can use a generator based approach there, too.

borlafu

781 silver badge6 bronze badges

answered Mar 12, 2009 at 10:52

5

Obscure [but fun] answer:

>>> sum[zip[*list_of_pairs][0]]
9

Or when zip's are iterables only this should work:

>>> sum[zip[*list_of_pairs].__next__[]]
9

SilentGhost

293k64 gold badges301 silver badges291 bronze badges

answered Mar 12, 2009 at 11:19

Ali AfsharAli Afshar

40.1k12 gold badges90 silver badges109 bronze badges

2

Below is sample code, you can also specify the list range.

def test_lst_sum[]:
    lst = [1, 3, 5]
    print sum[lst]  # 9
    print sum[lst[1:]]  # 8

    print sum[lst[5:]]  # 0  out of range so return 0
    print sum[lst[5:-1]]  # 0

    print sum[lst[1: -1]]  # 3

    lst_tp = [['33', 1], ['88', 2], ['22', 3], ['44', 4]]
    print sum[x[1] for x in lst_tp[1:]]  # 9

answered Dec 27, 2017 at 6:55

JayhelloJayhello

5,2953 gold badges46 silver badges54 bronze badges

If you don't mind converting it to a numpy array, you can use np.sum over axis=0 as given here

answered Aug 5, 2018 at 7:32

mithunpaulmithunpaul

3,06820 silver badges19 bronze badges

                s,p=0,0
                for i in l:
                  s=s+i[0]
                  p=p+i[1]
               print[tuple[s,p]]
  1. enter code here

answered Mar 4, 2020 at 14:35

1

Can you sum tuples in Python?

The built-in sum[] function in Python is used to return the sum of an iterable. To get the sum total of a tuple of numbers, you can pass the tuple as an argument to the sum[] function.

How do you sum two tuples in Python?

To add two tuples element-wise: Use the zip function to get an iterable of tuples with the corresponding items. Use a list comprehension to iterate over the iterable. On each iteration, pass the tuple to the sum[] function.

How do you sum a list in Python?

Python provides an inbuilt function sum[] which sums up the numbers in the list. Syntax: sum[iterable, start] iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers. start : this start is added to the sum of numbers in the iterable.

How do you add tuple values together?

Concatenating and Multiplying Tuples Concatenation is done with the + operator, and multiplication is done with the * operator. Because the + operator can concatenate, it can be used to combine tuples to form a new tuple, though it cannot modify an existing tuple. The * operator can be used to multiply tuples.

Chủ Đề