Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line Sum List

#1
Python One Line Sum List

Article summary: Here’s a quick visual overview of the contents of this tutorial.

How to sum over all values in a given Python list? https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 768px) 100vw, 768px" />
  • Flat List: To sum over a list of numbers in a single line of Python code, use Python’s built-in function 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: 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.

a = [1, 2, 3]

You want to calculate the sum of all values in the list—using only a single line of Python code!

# RESULT: 6

Solution: Python’s built-in sum() 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 sum() 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.

a = [1, 2, 3] print(sum(a))
# 6

How does it work? The syntax is sum(iterable, start=0):


Argument Description
iterable Sum over all elements in the iterable. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements.
Example: sum([1, 2, 3]) returns 1+2+3=6.
start (Optional.) The default start value is 0. If you define another start value, the sum of all values in the iterable will be added to this start value.
Example: sum([1, 2, 3], 9) returns 9+1+2+3=15.



Exercise: Try to modify the sequence so that the sum is 30 in our interactive Python shell:

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 [[1, 2], [3, 4], [5, 6]] in Python?

Solution: Use a generator expression to flatten the values in the nested list and pass the resulting iterable into the sum() function.

Code: The following code creates a list of lists:

a = [[1, 2], [3, 4], [5, 6]]

To sum over the values in the list of lists, use the following one-liner:

print(sum(x for y in a for x in y))

The output is printed on the shell:

# OUTPUT: 21

But how does it work? The main part of the code is the generator expression x for y in a for x in y that flattens the list.

  • The part x for y in a for x in y iterates over all elements y in the nested list a.
  • The part x for y in a for x in y iterates over all elements y in the inner list y.
  • The part x for y in a for x in y stores the inner element in the iterable.

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.

Python One-Liners

Python One-Liners will 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!!



https://www.sickgaming.net/blog/2020/09/...-sum-list/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Read a File Line-By-Line and Store Into a List? xSicKxBot 0 4 Yesterday, 06:12 PM
Last Post: xSicKxBot
  [Tut] How To Kill A Thread In Python? xSicKxBot 0 6 Yesterday, 05:40 AM
Last Post: xSicKxBot
  [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 12 10-16-2020, 10:30 PM
Last Post: xSicKxBot
  [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 18 10-10-2020, 08:24 PM
Last Post: xSicKxBot
  [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 19 10-09-2020, 06:13 PM
Last Post: xSicKxBot
  [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 33 10-02-2020, 04:24 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 32 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 34 09-29-2020, 09:02 PM
Last Post: xSicKxBot
  [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 38 09-28-2020, 02:36 AM
Last Post: xSicKxBot
  [Tut] List Changes After Assignment — How to Clone or Copy It? xSicKxBot 0 37 09-27-2020, 12:14 AM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
Xbox Wire - Xbox Insider Release Notes –...
Last Post: xSicKxBot
Today 02:31 PM
» Replies: 0
» Views: 2
News - Video: The lighting technology of...
Last Post: xSicKxBot
Today 02:30 PM
» Replies: 0
» Views: 3
News - Talking Point: What Are You Playi...
Last Post: xSicKxBot
Today 02:22 PM
» Replies: 0
» Views: 2
News - Of Course Scalpers Are Already Li...
Last Post: xSicKxBot
Today 02:22 PM
» Replies: 0
» Views: 2
News - Xbox Could Offer Streaming Stick ...
Last Post: xSicKxBot
Today 02:21 PM
» Replies: 0
» Views: 3
(Indie Deal) FREE Ghost Sweeper, ? NBA 2...
Last Post: xSicKxBot
Today 08:16 AM
» Replies: 0
» Views: 4
(Free Game Key) BigFish Game of Your Cho...
Last Post: xSicKxBot
Today 08:16 AM
» Replies: 0
» Views: 5
News - Random: Not Everyone Is Happy Wit...
Last Post: xSicKxBot
Today 08:15 AM
» Replies: 0
» Views: 3
News - Xbox Could Offer Streaming Stick ...
Last Post: xSicKxBot
Today 08:15 AM
» Replies: 0
» Views: 4
microStudio Game Engine Hands-On
Last Post: xSicKxBot
Today 12:22 AM
» Replies: 0
» Views: 6

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020