AJD98
AJD98

Reputation: 105

How to add sums of lists in python

num_list_1 = [1,2,3,4]

sum of num_list_1 = 10

num_list_2 = [5,6,7,8]

sum of num_list_2 = 26

how would I be able to sum together num_list_1 and num_list_2.

I've tried doing it myself however as it is a list it wont let me concatenate them.

Upvotes: 3

Views: 213

Answers (7)

Sunil Game
Sunil Game

Reputation: 29

You can use:

>>> num_list_1 = [1,2,3,4]
>>> num_list_2 = [5,6,7,8]
>>> sum(num_list_1+num_list_2)
>>> 36

Upvotes: 0

jpp
jpp

Reputation: 164613

sum takes an iterable, so you can use itertools.chain to chain your lists and feed the resulting iterable to sum:

from itertools import chain

num_list_1 = [1,2,3,4]
num_list_2 = [5,6,7,8]

res = sum(chain(num_list_1, num_list_2))  # 36

Upvotes: 0

Lokesh Soni
Lokesh Soni

Reputation: 59

+ acts as concatenating in case of lists, so sum(num_list_1 + num_list_2) will help

Upvotes: 1

Ankit Singh
Ankit Singh

Reputation: 247

First Define both lists

num_list_1 = [1,2,3,4]
num_list_2 = [5,6,7,8]

then use Sum() For Both list

print(sum(num_list_1) + sum (num_list_2))

Also You Can Do This :

print(sum(num_list_1+ num_list_2))

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

if you have several lists (more than 2) you could sum the sums by applying map to the results:

sum(map(sum,(num_list_1,num_list_2)))

Upvotes: 1

Mayank Porwal
Mayank Porwal

Reputation: 34046

Get the sum of each list individually, and then sum the both scalar values to get the total_sum:

In [1733]: num_list_1 = [1,2,3,4]

In [1734]: num_list_2 = [5,6,7,8]

In [1737]: sum(num_list_1) + sum(num_list_2)
Out[1737]: 36

Upvotes: 7

magicleon94
magicleon94

Reputation: 5162

You could sum the concatenation of the two lists:

sum(num_list_1+num_list_2)

This is what I get using the python console:

>>>num_list_1 = [1,2,3,4]
>>>num_list_2 = [5,6,7,8]
>>>sum(num_list_1+num_list_2)
>>>36

Or you could just sum the sums:

sum(num_list_1) + sum(num_list_2)

which leads to the same output but in a probably faster way:

>>>num_list_1 = [1,2,3,4]
>>>num_list_2 = [5,6,7,8]
>>>sum(num_list_1) + sum(num_list_2)
>>>36

Upvotes: 2

Related Questions