Python sum list of string numbers

In Python, programmers work with a lot of lists. Sometimes, it is necessary to find out the sum of the elements of the lists for other operations within the program.

In this article, we will take a look at the following ways to calculate sum of all elements in a Python list:

1) Using sum() Method

Python provides an inbuilt function called sum() which sums up the numbers in a list.

Syntax

Sum(iterable, start)
  • Iterable – It can be a list, a tuple or a dictionary. Items of the iterable have to be numbers.  
  • Start – This number is added to the resultant sum of items. The default value is 0.

The method adds the start and the iterable elements from left to right.

Example:

sum(list) sum(list, start)

Code Example:

# Python code to explain working on sum() method # Declare list of numbers numlist = [2,4,2,5,7,9,23,4,5] numsum = sum(numlist) print('Sum of List: ',numsum) # Example with start numsum = sum(numlist, 5) print('Sum of List: ',numsum)

Output:

Sum of List:  61 Sum of List:  66

Explanation 

Here, you can see that the sum() method takes two parameters – numlist, the iterable and 5 as the start value. The final value is 61 (without the start value) and 66 (with the start value 5 added to it).  

2) Using for Loop

# Python code to calculate sum of integer list # Using for loop # Declare list of numbers numlist = [2,4,2,5,7,9,23,4,5] # Calculate sum of list numsum=0 for i in numlist: numsum+=i print('Sum of List: ',numsum)

Output

Sum of List:  61

Explanation

Here, a for loop is run over the list called numlist. With each iteration, the elements of the list are added. The result is 61 which is printed using the print statement.

3) Sum of List Containing String Value

# Python code to calculate sum of list containing integer as string # Using for loop # Declare list of numbers as string numlist = ['2','4','2','5','7','9','23','4','5'] # Calculate sum of list numsum=0 for i in numlist: numsum+=int(i) print('Sum of List: ',numsum)

Output

Sum of List:  61

Here, the list called numlist contains integers as strings. Inside the for loop, these string elements are added together after converting them into integers, using the int() method.

4) Using While Loop

# Python code to calculate sum of list containing integer as string # Using While loop # Declare list of numbers as string numlist = [2,4,2,5,7,9,23,4,5] # Declare function to calculate sum of given list def listsum(numlist): total = 0 i = 0 while i < len(numlist): total = total + numlist[i] i = i + 1 return total # Call Function # Print sum of list totalsum = listsum(numlist); print('Sum of List: ', totalsum)

Explanation

In this program, elements of the numlist array are added using a while loop. The loop runs until the variable i is less than the length of the numlist array. The final summation is printed using the value assigned in the totalsum variable.

Conclusion

Using a for loop or while loop is great for summing elements of a list. But the sum() method is faster when you are handling huge lists of elements.    

In this short tutorial, we look at how we can use Python to find the sum() of a list. We look at the various methods to do this along with their limitations.

Table of Contents - Python Sum List:

  1. Using Sum to find the sum of a List
  2. How to use the sum() function?
  3. Limitation and Caverts - Python Sum List
  4. Other Related Concepts

Python Sum List:

While using Python, there are sure to be numerous use cases where you might have to calculate the sum of an iterable. For the purpose of this blog, we mainly focus on lists; however, the same method can be applied to other iterables as well.

An example of a use case is the use of sum() to return the sum of a list that contains the weekly income of employees to calculate monthly income.

How to use the sum() function?

The sum() function returns the sum of an iterable. Sum() takes a list (iterable) and returns the sum of the numbers within the list.

The syntax is as follows:

sum(iterable, start)

Parameters:

  1. Iterable - Required, iterable can be a list, tuples, and dictionary
  2. Start - Optional, if passed it the value will be added returned sum


Code and Explanation:

#Using range to create list of numbers numbers = list(range(0,10)) sum_numbers = sum(numbers) print(sum_numbers) #Output - 45 #Passing an argument as start sum_numbers = sum(numbers, 10) print(sum_numbers) #Output - 55 As seen in the above code snippet, the sum() function is used to add the values in the range that has been specified. You can similarly use the function for various operations.

Limitations and Caveats - Python Sum List

A common error that arises while using the sum() function, is when the list contains a string. Since it is not possible to add int values in strings, Python returns a TypeError. Let us look at such an instance.#Creating a list of number and a string numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "10"] sum_numbers = sum(numbers) print(sum_numbers) Python returns this output:
Traceback (most recent call last): File "C:\Users\Python\Using_sum.py", line 4, in sum_numbers = sum(numbers) TypeError: unsupported operand type(s) for +: 'int' and 'str'
As explained, the int value in the string causes the TypeError. Other than this limitation, you can make use of the sum() function in Python with ease for all summing operations.

The adjacent elements in the array are compared and the positions are swapped if the first element is greater than the second. In this fashion, the largest value "bubbles" to the top.

You might find this useful when you want to execute a particular script if the array is empty - like enabling or disabling buttons based on if there is any input in the required field, etc. 

In this article, we cover the different methods to compare two arrays and check if they are equal using javascript. In this process we will also understand the pros and cons of various methods used. 

Examples of how to sum a list of numbers in python:

Using the sum() function

To add all the elements of a list, a solution is to use the built-in function sum(), illustration:

>>> list = [1,2,3,4] >>> sum(list) 10

Example with float numbers:

>>> l = [3.1,2.5,6.8] >>> sum(l) 12.399999999999999

Note: it is possible to round the sum (see also Floating Point Arithmetic: Issues and Limitations):

>>> round(sum(l),1) 12.4

Iterate through the list:

Example using a for loop:

>>> list = [1,2,3,4] >>> tot = 0 >>> for i in list: ... tot = tot + i ... >>> tot 10

Sum a list including different types of elements

Another example with a list containing: integers, floats and strings:

>>> l = ['a',1,'f',3.2,4] >>> sum([i for i in l if isinstance(i, int) or isinstance(i, float)]) 8.2

Merge a list of "strings":

Note: in the case of a list of strings the function sum() does not work:

>>> list = ['a','b','c','d'] >>> sum(list) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'

use the function join() instead:

>>> ','.join(list) 'a,b,c,d' >>> ' '.join(list) 'a b c d'

References

l = [3.1,2.5,6.8] sum(l)

12.399999999999999

In this example, how do I prevent this error? Because 3.1+2.5+6.8=12.4

good comment, a simple solution here would be (see: Floating Point Arithmetic: Issues and Limitations for further explanations):

>>> round(sum(l),1) 12.4

Note: using a for loop also returns 12.399999999999999

>>> tot = 0 >>> for x in l: ... tot = tot + x ... >>> tot 12.399999999999999

Video liên quan

Chủ đề