Sum parts of 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 listor any other iterable for that matter. [Official Docs]

The syntax is sum[iterable, start=0]:

ArgumentDescription
iterableSum 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.

Check out the Python Freelancer Webinar and KICKSTART your coding career!

Code: Lets check out a practical example!

lst = [1, 2, 3, 4, 5, 6] print[sum[lst]] # 21 print[sum[lst, 10]] # 31

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

Lets explore some important details regarding the sum[] function in Python.

Table of Contents

  • Errors
  • Python Sum List Time Complexity
  • Python Sum List of Strings
  • Python Sum List of Lists
  • Python Sum List While Loop
  • Python Sum List For Loop
  • Python Sum List with List Comprehension
  • Python Sum List of Tuples Element Wise
  • Python Sum List Slice
  • Python Sum List Condition
  • Python Sum List Ignore None
  • Python Sum List Ignore Nan
  • Where to Go From Here?

Errors

A number of errors can happen if you use the sum[] function in Python.

TypeError: Python will throw a TypeError if you try to sum over elements that are not numerical. Heres an example:

# Demonstrate possible execeptions lst = ['Bob', 'Alice', 'Ann'] # WRONG: s = sum[lst]

If you run this code, youll get the following error message:

Traceback [most recent call last]: File "C:\Users\xcent\Desktop\code.py", line 3, in s = sum[lst] TypeError: unsupported operand type[s] for +: 'int' and 'str'

Python tries to perform string concatenation using the default start value of 0 [an integer]. Of course, this fails. The solution is simple: sum only over numerical values in the list.

If you try to hack Python by using an empty string as start value, youll get the following exception:

# Demonstrate possible execeptions lst = ['Bob', 'Alice', 'Ann'] # WRONG: s = sum[lst, '']

Output:

Traceback [most recent call last]: File "C:\Users\xcent\Desktop\code.py", line 5, in s = sum[lst, ''] TypeError: sum[] can't sum strings [use ''.join[seq] instead]

You can get rid of all those errors by summing only over numerical elements in the list.

[For more information about the join[] method, check out this blog article.]

Python Sum List Time Complexity

The time complexity of the sum[] function is linear in the number of elements in the iterable [list, tuple, set, etc.]. The reason is that you need to go over all elements in the iterable and add them to a sum variable. Thus, you need to touch every iterable element once.

Python Sum List of Strings

Problem: How can you sum a list of strings such as ['python', 'is', 'great']? This is called string concatenation.

Solution: Use the join[] method of Python strings to concatenate all strings in a list. The sum[] function works only on numerical input data.

Code: The following example shows how to sum up [i.e., concatenate] all elements in a given list of strings.

# List of strings lst = ['Bob', 'Alice', 'Ann'] print[''.join[lst]] # BobAliceAnn print[' '.join[lst]] # Bob Alice Ann

Python Sum List of Lists

Problem: How can you sum a list of lists such as [[1, 2], [3, 4], [5, 6]] in Python?

Solution: Use a simple for loop with a helper variable to concatenate all lists.

Code: The following code concatenates all lists into a single list.

# List of lists lst = [[1, 2], [3, 4], [5, 6]] s = [] for x in lst: s.extend[x] print[s] # [1, 2, 3, 4, 5, 6]

The extend[] method is little-known in Pythonbut its very effective to add a number of elements to a Python list at once. Check out my detailed tutorial on this Finxter blog.

Python Sum List While Loop

Problem: How can you sum over all list elements using a while loop [without sum[]]?

Solution: Create an aggregation variable and iteratively add another element from the list.

Code: The following code shows how to sum up all numerical values in a Python list without using the sum[] function.

# list of integers lst = [1, 2, 3, 4, 5] # aggregation variable s = 0 # index variable i = 0 # sum everything up while i4].

# create the list lst = [5, 8, 12, 2, 1, 3] # filter the list filtered = [x for x in lst if x>4] # remaining list: [5, 8, 12] # sum over the filtered list s = sum[filtered] # print everything print[s] # 25

Need a refresher on list comprehension? Check out my in-depth tutorial on the Finxter blog.

Python Sum List Ignore None

Problem: Given is a list of numerical values that may contain some values None. How to sum over all values that are not the value None?

Example: Say, youve got the list lst = [5, None, None, 8, 12, None, 2, 1, None, 3] and you want to sum over all values that are not None.

Solution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain [that are different from None]. You see, thats a special case of the previous paragraph that checks for a general condition. Then, use the sum[] function to sum over the remaining values.

Code: The following code sums over all values that are not None.

# create the list lst = [5, None, None, 8, 12, None, 2, 1, None, 3] # filter the list filtered = [x for x in lst if x!=None] # remaining list: [5, 8, 12, 2, 1, 3] # sum over the filtered list s = sum[filtered] # print everything print[s] # 31

A similar thing can be done with the value Nan that can disturb your result if you arent careful.

Python Sum List Ignore Nan

Problem: Given is a list of numerical values that may contain some values nan [=not a number]. How to sum over all values that are not the value nan?

Example: Say, youve got the list lst = [1, 2, 3, float["nan"], float["nan"], 4] and you want to sum over all values that are not nan.

Solution: Use list comprehension to filter the list so that only the elements that satisfy the condition remain [that are different from nan]. You see, thats a special case of the previous paragraph that checks for a general condition. Then, use the sum[] function to sum over the remaining values.

Code: The following code sums over all values that are not nan.

# for checking isnan[x] import math # create the list lst = [1, 2, 3, float["nan"], float["nan"], 4] # forget to ignore 'nan' print[sum[lst]] # nan # ignore 'nan' print[sum[[x for x in lst if not math.isnan[x]]]] # 10

Phew! Quite some stuff. Thanks for reading through this whole article! I hope youve learned something out of this tutorial and remain with the following recommendation:

Where to Go From Here?

Enough theory. Lets get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. Thats how you polish the skills you really need in practice. After all, whats the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

If your answer is YES!, consider becoming a Python freelance developer! Its the best way of approaching the task of improving your Python skillseven if you are a complete beginner.

Join my free webinar How to Build Your High-Income Skill Python and watch how I grew my coding business online and how you can, toofrom the comfort of your own home.

Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. Hes author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Video liên quan

Chủ Đề