TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python Sum Example

Use the sum method on a list of integers. Understand when TypeError is caused by sum.
Sum. A list contains the numbers 10, 20 and 5. Its sum is 35. We can a for-loop to iterate and add up the element values. Or we can use a simpler built-in method.
Two arguments. The sum() built-in receives two arguments. The first is an iterable collection like list—these elements are summed. The second argument is added to the sum.
An example. Here we introduce a list with three integers in it. We sum those integers with the sum() built-in method. And then we use sum with 2 arguments.Built-ins

Argument 1: An iterable like a list we want to sum. The list must have summable elements like integers, not sub lists.

Argument 2: A value that is added to the sum of the iterable's elements. We can use this argument to sum previous sums.

Python program that uses sum, two arguments values = [10, 20, 5] # The sum of the 3 values is this number. result = sum(values) print(result) # Use sum with two arguments. # ... The second argument is added to the element sum. result = sum(values, 1000) print(result) Output 35 1035
Error in summing. We cannot sum nested iterables. Instead sum() only counts up top-level elements in our list. A nested list leads to a TypeError.Nested list
Python program that uses sum, nested list error # This list has a nested list element. # ... It cannot be summed with sum. values = [10, [20, 30]] # This will cause a TypeError. result = sum(values) print(result) Output Traceback (most recent call last): File "C:\programs\file.py", line 9, in <module> result = sum(values) TypeError: unsupported operand type(s) for +: 'int' and 'list'
Fsum example. The sum() built-in will work with float numbers like 1.5. But it may return a less-accurate result than the math.fsum specialty method.Math: fsum
A review. Why use sum? Why not just loop over elements and add them up? In some programs, sum() leads to simpler, more maintainable code—but not always.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf