09-08-2020, 03:43 PM
Python One Line Sum List
Article summary: Here’s a quick visual overview of the contents of this tutorial.
![[Image: pythononelinesumlist-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/09/pythononelinesumlist-1024x576.jpg)
Method 1: Sum over a Flat List in One Line
Problem: How to sum over all values in a given Python list?
Example: Given the following list.
You want to calculate the sum of all values in the list—using only a single line of Python code!
Solution: Python’s built-in function helps you to sum over all values in an iterable, such as a Python list.
Summing up a list of numbers appears everywhere in coding. Fortunately, Python provides the built-in function to sum over all elements in a Python list—or any other iterable for that matter. (Official Docs)
Code: Here’s the minimal code example.
How does it work? The syntax is:
Argument |
Description
|
Sum over all elements in the. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements.
Example: returns .
|
(Optional.) The default start value is 0. If you define another start value, the sum of all values in the will be added to this start value.
Example: returns .
Exercise: Try to modify the sequence so that the sum is 30 in our interactive Python shell:
https://repl.it/@finxter/sumpythonlist?lite=true
Method 2: Sum over a Nested List of Lists in One Line
Problem: Given multiple lists in a list of lists. How can you sum over all values in a list of lists such as in Python?
Solution: Use a generator expression to flatten the values in the nested list and pass the resulting iterable into the function.
Code: The following code creates a list of lists:
To sum over the values in the list of lists, use the following one-liner:
The output is printed on the shell:
But how does it work? The main part of the code is the generator expression that flattens the list.
Here’s a recap on the technique of list comprehension.
To learn more about different ways to sum() elements in a list, check out my detailed blog tutorial:
Related Tutorial: Python sum() List — Ultimate Guide
Python One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners Now!!
Article summary: Here’s a quick visual overview of the contents of this tutorial.
![[Image: pythononelinesumlist-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/09/pythononelinesumlist-1024x576.jpg)
- Flat List: To sum over a list of numbers in a single line of Python code, use Python’s built-in function .Code:
sum(list)
- Nested List: To sum over a list of lists in one line Python, use a generator expression to flatten the list and pass the result into the function: .Code:
sum(x for y in list for x in y)
Method 1: Sum over a Flat List in One Line
Problem: How to sum over all values in a given Python list?
Example: Given the following list.
Code:
a = [1, 2, 3]You want to calculate the sum of all values in the list—using only a single line of Python code!
Code:
# RESULT: 6Solution: Python’s built-in
Code:
sum()Summing up a list of numbers appears everywhere in coding. Fortunately, Python provides the built-in
Code:
sum()Code: Here’s the minimal code example.
Code:
a = [1, 2, 3] print(sum(a))
# 6How does it work? The syntax is
Code:
sum(iterable, start=0)Argument |
Description
Code:
iterableSum over all elements in the
Code:
iterableExample:
Code:
sum([1, 2, 3])Code:
1+2+3=6Code:
start(Optional.) The default start value is 0. If you define another start value, the sum of all values in the
Code:
iterableExample:
Code:
sum([1, 2, 3], 9)Code:
9+1+2+3=15Exercise: Try to modify the sequence so that the sum is 30 in our interactive Python shell:
https://repl.it/@finxter/sumpythonlist?lite=true
Method 2: Sum over a Nested List of Lists in One Line
Problem: Given multiple lists in a list of lists. How can you sum over all values in a list of lists such as
Code:
[[1, 2], [3, 4], [5, 6]]Solution: Use a generator expression to flatten the values in the nested list and pass the resulting iterable into the
Code:
sum()Code: The following code creates a list of lists:
Code:
a = [[1, 2], [3, 4], [5, 6]]To sum over the values in the list of lists, use the following one-liner:
Code:
print(sum(x for y in a for x in y))The output is printed on the shell:
Code:
# OUTPUT: 21But how does it work? The main part of the code is the generator expression
Code:
x for y in a for x in y- The part iterates over all elementsCode:
x for y in a for x in yin the nested listCode:y.Code:a
- The part iterates over all elementsCode:
x for y in a for x in yin the inner listCode:y.Code:y
- The part stores the inner element in the iterable.Code:
x for y in a for x in y
Here’s a recap on the technique of list comprehension.
To learn more about different ways to sum() elements in a list, check out my detailed blog tutorial:
Related Tutorial: Python sum() List — Ultimate Guide
Python One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
• Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
• Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
• Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
• Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Get your Python One-Liners Now!!

