Movatterモバイル変換


[0]ホーム

URL:


— FREE Email Series —

🐍 Python Tricks 💌

Python Tricks Dictionary Merge

🔒 No spam. Unsubscribe any time.

Browse TopicsGuided Learning Paths
Basics Intermediate Advanced
apibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnumpyprojectspythontestingtoolsweb-devweb-scraping

Table of Contents

Recommended Video Course
Summing Values the Pythonic Way With sum()

Python's sum(): The Pythonic Way to Sum Values

Python's sum(): The Pythonic Way to Sum Values

byLeodanis Pozo RamosReading time estimate 27mbasicspython

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:Summing Values the Pythonic Way With sum()

Python’s built-in functionsum() is an efficient andPythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, sosum() is a pretty handy tool for a Python programmer.

As an additional and interesting use case, you can concatenatelists and tuples usingsum(), which can be convenient when you need to flatten a list of lists.

In this tutorial, you’ll learn how to:

  • Sum numeric values by hand usinggeneral techniques and tools
  • UsePython’ssum() to add several numeric values efficiently
  • Concatenate lists and tuples withsum()
  • Usesum() to approach commonsummation problems
  • Use appropriate values for thearguments insum()
  • Decide betweensum() andalternative tools to sum and concatenate objects

This knowledge will help you efficiently approach and solve summation problems in your code using eithersum() or other alternative and specialized tools.

Free Bonus:Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Understanding the Summation Problem

Summing numeric values together is a fairly common problem in programming. For example, say you have a list of numbers [1, 2, 3, 4, 5] and want to add them together to compute their total sum. With standard arithmetic, you’ll do something like this:

1 + 2 + 3 + 4 + 5 = 15

As far as math goes, this expression is pretty straightforward. It walks you through a short series of additions until you find the sum of all the numbers.

It’s possible to do this particular calculation by hand, but imagine some other situations where it might not be so possible. If you have a particularly long list of numbers, adding by hand can be inefficient and error-prone. What happens if you don’t even know how many items are in the list? Finally, imagine a scenario where the number of items you need to add changes dynamically or unpredictably.

In situations like these, whether you have a long or short list ofnumbers, Python can be quite useful to solvesummation problems.

If you want to sum the numbers by creating your own solution from scratch, then you can try using afor loop:

Python
>>>numbers=[1,2,3,4,5]>>>total=0>>>fornumberinnumbers:...total+=number...>>>total15

Here, you first createtotal and initialize it to0. Thisvariable works as anaccumulator in which you store intermediate results until you get the final one. The loop iterates throughnumbers and updatestotal by accumulating each successive value using anaugmented assignment.

You can also wrap thefor loop in afunction. This way, you can reuse the code for different lists:

Python
>>>defsum_numbers(numbers):...total=0...fornumberinnumbers:...total+=number...returntotal...>>>sum_numbers([1,2,3,4,5])15>>>sum_numbers([])0

Insum_numbers(), you take aniterable—specifically, a list of numeric values—as an argument andreturn the total sum of the values in the input list. If the input list is empty, then the function returns0. Thefor loop is the same one that you saw before.

You can also userecursion instead of iteration. Recursion is afunctional programming technique where a function is called within its own definition. In other words, a recursive function calls itself in a loop:

Python
>>>defsum_numbers(numbers):...iflen(numbers)==0:...return0...returnnumbers[0]+sum_numbers(numbers[1:])...>>>sum_numbers([1,2,3,4,5])15

When you define a recursive function, you take the risk of running into an infinite loop. To prevent this, you need to define both abase case that stops the recursion and arecursive case to call the function and start the implicit loop.

In the above example, the base case implies that the sum of a zero-length list is0. The recursive case implies that the total sum is the first value,numbers[0], plus the sum of the rest of the values,numbers[1:]. Because the recursive case uses a shorter sequence on each iteration, you expect to run into the base case whennumbers is a zero-length list. As a final result, you get the sum of all the items in your input list,numbers.

Note: In this example, if you don’t check for an empty input list (your base case), thensum_numbers() will never run into an infinite recursive loop. When yournumbers list reaches a length of0, the code tries to access an item from the empty list, which raises anIndexError and breaks the loop.

With this kind of implementation, you’ll never get a sum from this function. You’ll get anIndexError every time.

Another option to sum a list of numbers in Python is to usereduce() fromfunctools. To get the sum of a list of numbers, you can pass eitheroperator.add or an appropriatelambda function as the first argument toreduce():

Python
>>>fromfunctoolsimportreduce>>>fromoperatorimportadd>>>reduce(add,[1,2,3,4,5])15>>>reduce(add,[])Traceback (most recent call last):...TypeError:reduce() of empty sequence with no initial value>>>reduce(lambdax,y:x+y,[1,2,3,4,5])15

You can callreduce() with a reduction, orfolding,function along with aniterable as arguments. Thenreduce() uses the input function to processiterable and returns a single cumulative value.

In the first example, the reduction function isadd(), which takes two numbers and adds them together. The final result is the sum of the numbers in the inputiterable. As a drawback,reduce() raises aTypeError when you call it with an emptyiterable.

In the second example, the reduction function is alambda function that returns the addition of two numbers.

Since summations like these are commonplace in programming, coding a new function every time you need to sum some numbers is a lot of repetitive work. Additionally, usingreduce() isn’t the most readable solution available to you.

Python provides a dedicated built-in function to solve this problem. The function is conveniently calledsum(). Since it’s a built-in function, you can use it directly in your code withoutimporting anything.

Getting Started With Python’ssum()

Readability is one of the most important principles behindPython’s philosophy. Visualize what you are asking a loop to do when summing a list of values. You want it to loop over some numbers, accumulate them in an intermediate variable, and return the final sum. However, you can probably imagine a more readable version of summation that doesn’t need a loop. You want Python to take some numbers and sum them together.

Now think about howreduce() does summation. Usingreduce() is arguably less readable and less straightforward than even the loop-based solution.

This is whyPython 2.3 addedsum() as a built-in function to provide a Pythonic solution to the summation problem.Alex Martelli contributed the function, which nowadays is the preferred syntax for summing a list of values:

Python
>>>sum([1,2,3,4,5])15>>>sum([])0

Wow! That’s neat, isn’t it? It reads like plain English and clearly communicates the action you’re performing on the input list. Usingsum() is way more readable than afor loop or areduce() call. Unlikereduce(),sum() doesn’t raise aTypeError when you provide an empty iterable. Instead, it understandably returns0.

You can callsum() with the following two arguments:

  1. iterable is a required argument that can hold any Python iterable. The iterable typically contains numeric values but can also containlists or tuples.
  2. start is an optional argument that can hold an initial value. This value is then added to the final result. It defaults to0.

Internally,sum() addsstart plus the values initerable from left to right. The values in the inputiterable are normally numbers, but you can also use lists and tuples. The optional argumentstart can accept a number, list, or tuple, depending on what is passed toiterable. It can’t take astring.

In the following two sections, you’ll learn the basics of usingsum() in your code.

The Required Argument:iterable

Accepting any Python iterable as its first argument makessum() generic, reusable, andpolymorphic. Because of this feature, you can usesum() with lists, tuples,sets,range objects, anddictionaries:

Python
>>># Use a list>>>sum([1,2,3,4,5])15>>># Use a tuple>>>sum((1,2,3,4,5))15>>># Use a set>>>sum({1,2,3,4,5})15>>># Use a range>>>sum(range(1,6))15>>># Use a dictionary>>>sum({1:"one",2:"two",3:"three"})6>>>sum({1:"one",2:"two",3:"three"}.keys())6

In all these examples,sum() computes the arithmetic sum of all the values in the input iterable regardless of their types. In the two dictionary examples, both calls tosum() return the sum of the keys of the input dictionary. The first example sums the keys by default and the second example sums the keys because of the.keys() call on the input dictionary.

If your dictionary stores numbers in its values and you would like to sum these values instead of the keys, then you can do this by using.values() just like in the.keys() example.

You can also usesum() with alist comprehension as an argument. Here’s an example that computes the sum of the squares of a range of values:

Python
>>>sum([x**2forxinrange(1,6)])55

Python 2.4 addedgenerator expressions to the language. Again,sum() works as expected when you use a generator expression as an argument:

Python
>>>sum(x**2forxinrange(1,6))55

This example shows one of the most Pythonic techniques to approach the summation problem. It provides an elegant, readable, and efficient solution in a single line of code.

The Optional Argument:start

The second and optional argument,start, allows you to provide a value to initialize the summation process. This argument is handy when you need to process cumulative values sequentially:

Python
>>>sum([1,2,3,4,5],100)# Positional argument115>>>sum([1,2,3,4,5],start=100)# Keyword argument115

Here, you provide an initial value of100 tostart. The net effect is thatsum() adds this value to the cumulative sum of the values in the input iterable. Note that you can providestart as apositional argument or as akeyword argument. The latter option is way more explicit and readable.

If you don’t provide a value tostart, then it defaults to0. A default value of0 ensures the expected behavior of returning the total sum of the input values.

Summing Numeric Values

The primary purpose ofsum() is to provide a Pythonic way to add numeric values together. Up to this point, you’ve seen how to use the function to sum integer numbers. Additionally, you can usesum() with any other numeric Python types, such asfloat,complex,decimal.Decimal, andfractions.Fraction.

Here are a few examples of usingsum() with values of different numeric types:

Python
>>>fromdecimalimportDecimal>>>fromfractionsimportFraction>>># Sum floating-point numbers>>>sum([10.2,12.5,11.8])34.5>>>sum([10.2,12.5,11.8,float("inf")])inf>>>sum([10.2,12.5,11.8,float("nan")])nan>>># Sum complex numbers>>>sum([3+2j,5+6j])(8+8j)>>># Sum Decimal numbers>>>sum([Decimal("10.2"),Decimal("12.5"),Decimal("11.8")])Decimal('34.5')>>># Sum Fraction numbers>>>sum([Fraction(51,5),Fraction(25,2),Fraction(59,5)])Fraction(69, 2)

Here, you first usesum() withfloating-point numbers. It’s worth noting the function’s behavior when you use the special symbolsinf andnan in the callsfloat("inf") andfloat("nan"). The first symbol represents aninfinite value, sosum() returnsinf. The second symbol representsNaN (not a number) values. Since you can’t add numbers with non-numbers, you getnan as a result.

The other examples sum iterables ofcomplex,Decimal, andFraction numbers. In all cases,sum() returns the resulting cumulative sum using the appropriate numeric type.

Concatenating Sequences

Even thoughsum() is mostly intended to operate on numeric values, you can also use the function to concatenate sequences such as lists and tuples. To do that, you need to provide an appropriate value tostart:

Python
>>>num_lists=[[1,2,3],[4,5,6]]>>>sum(num_lists,start=[])[1, 2, 3, 4, 5, 6]>>># Equivalent concatenation>>>[1,2,3]+[4,5,6][1, 2, 3, 4, 5, 6]>>>num_tuples=((1,2,3),(4,5,6))>>>sum(num_tuples,start=())(1, 2, 3, 4, 5, 6)>>># Equivalent concatenation>>>(1,2,3)+(4,5,6)(1, 2, 3, 4, 5, 6)

In these examples, you usesum() to concatenate lists and tuples. This is an interesting feature that you can use to flatten a list of lists or a tuple of tuples. The key requirement for these examples to work is to select an appropriate value forstart. For example, if you want to concatenate lists, thenstart needs to hold a list.

In the examples above,sum() is internally performing a concatenation operation, so it works only with those sequence types that support concatenation, with the exception of strings:

Python
>>>num_strs=["123","456"]>>>sum(num_strs,"0")Traceback (most recent call last):  File"<stdin>", line1, in<module>TypeError:sum() can't sum strings [use ''.join(seq) instead]

When you try to usesum() toconcatenate strings, you get aTypeError. As the exception message suggests, you should usestr.join() to concatenate strings in Python. You’ll see examples of using this method later on when you get to the section onUsing Alternatives tosum().

Practicing With Python’ssum()

So far, you’ve learned the basics of working withsum(). You’ve learned how to use this function to add numeric values together and also to concatenate sequences such as lists and tuples.

In this section, you’ll look at some more examples of when and how to usesum() in your code. With these practical examples, you’ll learn that this built-in function is quite handy when you’re performing computations that require finding the sum of a series of numbers as an intermediate step.

You’ll also learn thatsum() can be helpful when you’re working with lists and tuples. A special example you’ll look at is when you need to flatten a list of lists.

Computing Cumulative Sums

The first example you’ll code has to do with how to take advantage of thestart argument for summing cumulative lists of numeric values.

Say you’re developing a system to manage the sales of a given product at several different points of sale. Every day, you get a sold units report from each point of sale. You need to systematically compute the cumulative sum to know how many units the whole company sold over the week. To solve this problem, you can usesum():

Python
>>>cumulative_sales=0>>>monday=[50,27,42]>>>cumulative_sales=sum(monday,start=cumulative_sales)>>>cumulative_sales119>>>tuesday=[12,32,15]>>>cumulative_sales=sum(tuesday,start=cumulative_sales)>>>cumulative_sales178>>>wednesday=[20,24,42]>>>cumulative_sales=sum(wednesday,start=cumulative_sales)>>>cumulative_sales264    ...

By usingstart, you set an initial value to initialize the sum, which allows you to add successive units to the previously computed subtotal. At the end of the week, you’ll have the company’s total count of sold units.

Calculating the Mean of a Sample

Another practical use case ofsum() is to use it as an intermediate calculation before doing further calculations. For example, say you need to calculate thearithmetic mean of a sample of numeric values. The arithmetic mean, also known as theaverage, is the total sum of the values divided by the number of values, ordata points, in the sample.

If you have the sample [2, 3, 4, 2, 3, 6, 4, 2] and you want to calculate the arithmetic mean by hand, then you can solve this operation:

(2 + 3 + 4 + 2 + 3 + 6 + 4 + 2) / 8 = 3.25

If you want to speed this up by using Python, you can break it up into two parts. The first part of this computation, where you are adding together the numbers, is a task forsum(). The next part of the operation, where you are dividing by 8, uses the count of numbers in your sample. To calculate yourdivisor, you can uselen():

Python
>>>data_points=[2,3,4,2,3,6,4,2]>>>sum(data_points)/len(data_points)3.25

Here, the call tosum() computes the total sum of the data points in your sample. Next, you uselen() to get the number of data points. Finally, you perform the required division to calculate the sample’s arithmetic mean.

In practice, you may want to turn this code into a function with some additional features, such as a descriptive name and a check for empty samples:

Python
>>># Python >= 3.8>>>defaverage(data_points):...if(num_points:=len(data_points))==0:...raiseValueError("average requires at least one data point")...returnsum(data_points)/num_points...>>>average([2,3,4,2,3,6,4,2])3.25>>>average([])Traceback (most recent call last):  File"<stdin>", line1, in<module>  File"<stdin>", line3, inaverageValueError:average requires at least one data point

Insideaverage(), you first check if the input sample has any data points. If not, then you raise aValueError with a descriptive message. In this example, you use thewalrus operator to store the number of data points in the variablenum_points so that you won’t need to calllen() again. Thereturn statement computes the sample’s arithmetic mean and sends it back to the calling code.

Note: Computing the mean of a sample of data is a common operation in statistics and data analysis. The Python standard library provides a convenient module calledstatistics to approach these kinds of calculations.

In thestatistics module, you’ll find a function calledmean():

Python
>>>fromstatisticsimportmean>>>mean([2,3,4,2,3,6,4,2])3.25>>>mean([])Traceback (most recent call last):...statistics.StatisticsError:mean requires at least one data point

Thestatistics.mean() function has very similar behavior to theaverage() function you coded earlier. When you callmean() with a sample of numeric values, you’ll get the arithmetic mean of the input data. When you pass an empty list tomean(), you’ll get astatistics.StatisticsError.

Note that when you callaverage() with a proper sample, you’ll get the desired mean. If you callaverage() with an empty sample, then you get aValueError as expected.

Finding the Dot Product of Two Sequences

Another problem you can solve usingsum() is finding thedot product of two equal-length sequences of numeric values. The dot product is the algebraic sum ofproducts of every pair of values in the input sequences. For example, if you have the sequences (1, 2, 3) and (4, 5, 6), then you can calculate their dot product by hand using addition and multiplication:

1 × 4 + 2 × 5 + 3 × 6 = 32

To extract successive pairs of values from the input sequences, you can usezip(). Then you can use a generator expression to multiply each pair of values. Finally,sum() can sum the products:

Python
>>>x_vector=(1,2,3)>>>y_vector=(4,5,6)>>>sum(x*yforx,yinzip(x_vector,y_vector))32

Withzip(), you generate a list of tuples with the values from each of the input sequences. The generator expression loops over each tuple while multiplying the successive pairs of values previously arranged byzip(). The final step is to add the products together usingsum().

The code in the above example works. However, the dot product is defined for sequences of equal length, so what happens if you provide sequences with different lengths? In that case,zip() ignores the extra values from the longest sequence, which leads to an incorrect result.

To deal with this possibility, you can wrap the call tosum() in a custom function and provide a proper check for the length of the input sequences:

Python
>>>defdot_product(x_vector,y_vector):...iflen(x_vector)!=len(y_vector):...raiseValueError("Vectors must have equal sizes")...returnsum(x*yforx,yinzip(x_vector,y_vector))...>>>dot_product((1,2,3),(4,5,6))32>>>dot_product((1,2,3,4),(5,6,3))Traceback (most recent call last):  File"<stdin>", line1, in<module>  File"<stdin>", line3, indot_productValueError:Vectors must have equal sizes

Here,dot_product() takes two sequences as arguments and returns their corresponding dot product. If the input sequences have different lengths, then the function raises aValueError.

Embedding the functionality in a custom function allows you to reuse the code. It also gives you the opportunity to name the function descriptively so that the user knows what the function does just by reading its name.

Flattening a List of Lists

Flattening a list of lists is a common task in Python. Say you have a list of lists and need to flatten it into a single list containing all the items from the original nested lists. You have options when deciding how toflatten lists in Python. For example, you can use afor loop, as in the following code:

Python
>>>defflatten_list(a_list):...flat=[]...forsublistina_list:...flat+=sublist...returnflat...>>>matrix=[...[1,2,3],...[4,5,6],...[7,8,9],...]>>>flatten_list(matrix)[1, 2, 3, 4, 5, 6, 7, 8, 9]

Insideflatten_list(), the loop iterates over all the nested lists contained ina_list. Then it concatenates them inflat using an augmented assignment operation (+=). As the result, you get a flat list with all the items from the original nested lists.

But hold on! You’ve already learned how to usesum() to concatenate sequences in this tutorial. Can you use that feature to flatten a list of lists like you did in the example above? Yes! Here’s how:

Python
>>>matrix=[...[1,2,3],...[4,5,6],...[7,8,9],...]>>>sum(matrix,[])[1, 2, 3, 4, 5, 6, 7, 8, 9]

That was quick! A single line of code andmatrix is now a flat list. However, usingsum() doesn’t seem to be the fastest solution.

Using a list comprehension is another common way to flatten a list of list in Python:

Python
>>>defflatten_list(a_list):...return[itemforsublistina_listforiteminsublist]...>>>matrix=[...[1,2,3],...[4,5,6],...[7,8,9],...]>>>flatten_list(matrix)[1, 2, 3, 4, 5, 6, 7, 8, 9]

This new version offlatten_list() uses a comprehension instead of a regularfor loop. However, thenested comprehensions can be challenging to read and understand.

Using.append() is another way to flatten a list of lists:

Python
>>>defflatten_list(a_list):...flat=[]...forsublistina_list:...foriteminsublist:...flat.append(item)...returnflat...>>>matrix=[...[1,2,3],...[4,5,6],...[7,8,9],...]>>>flatten_list(matrix)[1, 2, 3, 4, 5, 6, 7, 8, 9]

In this version offlatten_list(), someone reading your code can see that the function iterates over everysublist ina_list. In the secondfor loop, the function iterates over eachitem insublist to finally populate the newflat list with.append(). Arguably, readability can be an advantage of this solution.

Using Alternatives tosum()

As you’ve already learned,sum() is helpful for working with numeric values in general. However, when it comes to working with floating-point numbers, Python provides an alternative tool. Inmath, you’ll find a function calledfsum() that can help you improve the general precision of your floating-point computations.

You might have a task where you want to concatenate or chain several iterables so that you can work with them as one. For this scenario, you can look to theitertools module’s functionchain().

You might also have a task where you want to concatenate a list of strings. You’ve learned in this tutorial that there’s no way to usesum() for concatenating strings. This function just wasn’t built for string concatenation. The most Pythonic alternative is to usestr.join().

Summing Floating-Point Numbers:math.fsum()

If your code is constantly summing floating-point numbers withsum(), then you should consider usingmath.fsum() instead. This function performs floating-point computations more carefully thansum(), which improves the precision of your computation.

According to itsdocumentation,fsum() “avoids loss of precision by tracking multiple intermediate partial sums.” The documentation provides the following example:

Python
>>>frommathimportfsum>>>sum([.1,.1,.1,.1,.1,.1,.1,.1,.1,.1])0.9999999999999999>>>fsum([.1,.1,.1,.1,.1,.1,.1,.1,.1,.1])1.0

Withfsum(), you get a more precise result. However, you should note thatfsum() doesn’t solve therepresentation error in floating-point arithmetic. The following example uncovers this limitation:

Python
>>>frommathimportfsum>>>sum([0.1,0.2])0.30000000000000004>>>fsum([0.1,0.2])0.30000000000000004

In these examples, both functions return the same result. This is due to the impossibility of accurately representing both values0.1 and0.2 in binary floating-point:

Python
>>>f"{0.1:.28f}"'0.1000000000000000055511151231'>>>f"{0.2:.28f}"'0.2000000000000000111022302463'

Unlikesum(), however,fsum() can help you reduce floating-point error propagation when you add very large and very small numbers together:

Python
>>>frommathimportfsum>>>sum([1e-16,1,1e16])1e+16>>>fsum([1e-16,1,1e16])1.0000000000000002e+16>>>sum([1,1,1e100,-1e100]*10_000)0.0>>>fsum([1,1,1e100,-1e100]*10_000)20000.0

Wow! The second example is pretty surprising and totally defeatssum(). Withsum(), you get0.0 as a result. This is quite far away from the correct result of20000.0, as you get withfsum().

Concatenating Iterables Withitertools.chain()

If you’re looking for a handy tool for concatenating or chaining a series of iterables, then consider usingchain() fromitertools. This function can take multiple iterables and build aniterator that yields items from the first one, from the second one, and so on until it exhausts all the input iterables:

Python
>>>fromitertoolsimportchain>>>numbers=chain([1,2,3],[4,5,6],[7,8,9])>>>numbers<itertools.chain object at 0x7f0d0f160a30>>>>next(numbers)1>>>next(numbers)2>>>list(chain([1,2,3],[4,5,6],[7,8,9]))[1, 2, 3, 4, 5, 6, 7, 8, 9]

When you callchain(), you get an iterator of the items from the input iterables. In this example, you access successive items fromnumbers usingnext(). If you want to work with a list instead, then you can uselist() to consume the iterator and return a regular Python list.

chain() is also a good option for flattening a list of lists in Python:

Python
>>>fromitertoolsimportchain>>>matrix=[[1,2,3],[4,5,6],[7,8,9]]>>>list(chain(*matrix))[1, 2, 3, 4, 5, 6, 7, 8, 9]

To flatten a list of lists withchain(), you need to use theiterable unpacking operator (*). This operator unpacks all the input iterables so thatchain() can work with them and generate the corresponding iterator. The final step is to calllist() to build the desired flat list.

Concatenating Strings Withstr.join()

As you’ve already seen,sum() doesn’tconcatenate or join strings. If you need to do so, then the preferred and fastest tool available in Python isstr.join(). This method takes a sequence of strings as an argument and returns a new, concatenated string:

Python
>>>greeting=["Hello,","welcome to","Real Python!"]>>>" ".join(greeting)'Hello, welcome to Real Python!'

Using.join() is the most efficient and Pythonic way to concatenate strings. Here, you use a list of strings as an argument and build a single string from the input. Note that.join() uses the string on which you call the method as a separator during the concatenation. In this example, you call.join() on a string that consists of a single space character (" "), so the original strings fromgreeting are separated by spaces in your final string.

Conclusion

You can now use Python’s built-in functionsum() to add multiple numeric values together. This function provides an efficient, readable, and Pythonic way to solvesummation problems in your code. If you’re dealing with math computations that require summing numeric values, thensum() can be your lifesaver.

In this tutorial, you learned how to:

  • Sum numeric values usinggeneral techniques and tools
  • Add several numeric values efficiently usingPython’ssum()
  • Concatenate sequences usingsum()
  • Usesum() to approach commonsummation problems
  • Use appropriate values for theiterable andstart arguments insum()
  • Decide betweensum() andalternative tools to sum and concatenate objects

With this knowledge, you’re now able to add multiple numeric values together in a Pythonic, readable, and efficient way.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:Summing Values the Pythonic Way With sum()

🐍 Python Tricks 💌

Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

AboutLeodanis Pozo Ramos

Leodanis is a self-taught Python developer, educator, and technical writer with over 10 years of experience.

» More about Leodanis

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

MasterReal-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

MasterReal-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students.Get tips for asking good questions andget answers to common questions in our support portal.


Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics:basicspython

Recommended Video Course:Summing Values the Pythonic Way With sum()

Related Tutorials:

Keep reading Real Python by creating a free account or signing in:

Already have an account?Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Logo

Get the Python Cheat Sheet (Free PDF)

🔒 No spam. We take your privacy seriously.


[8]ページ先頭

©2009-2025 Movatter.jp