Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing elements in a list

Tags:

python

list

sum

Here is my code, I need to sum an undefined number of elements in the list. How to do this?

l = raw_input() l = l.split(' ') l.pop(0) 

My input: 3 5 4 9 After input I delete first element via l.pop(0). After .split(' ') my list is ['5', '4', '9'] and I need to sum all elements in this list.

In this case the sum is 18. Please notice that number of elements is not defined.

like image 938
treng Avatar asked Jul 05 '12 12:07

treng


People also ask

How do you sum items in a list in Python?

sum() function 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.

Can you sum a list in Python?

Python's built-in function sum() is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum() is a pretty handy tool for a Python programmer.


1 Answers

You can sum numbers in a list simply with the sum() built-in:

sum(your_list) 

It will sum as many number items as you have. Example:

my_list = range(10, 17) my_list [10, 11, 12, 13, 14, 15, 16]  sum(my_list) 91 

For your specific case:

For your data convert the numbers into int first and then sum the numbers:

data = ['5', '4', '9']  sum(int(i) for i in data) 18 

This will work for undefined number of elements in your list (as long as they are "numbers")

Thanks for @senderle's comment re conversion in case the data is in string format.

like image 69
Levon Avatar answered Sep 20 '22 15:09

Levon