Skip to content

Instantly share code, notes, and snippets.

@lsloan
Last active April 15, 2024 18:51
Show Gist options
  • Save lsloan/cb45188543078a538f68976b467e1897 to your computer and use it in GitHub Desktop.
Save lsloan/cb45188543078a538f68976b467e1897 to your computer and use it in GitHub Desktop.

Mathematical Summations in Python

Problem

I saw a video that claimed the following mathematical summation…

$$\sum_{\substack{i=0 \\ i\neq 4}}^{n} i$$

Can be implemented in Python as…

n = 10
i = 0
for i in range(n):
  if i != 4:
    i += 1

❌ WRONG!

What's wrong?

  • The loop variable, i is being modified, which can be a risky programming technique, depending on the language. In Python, it does nothing. This code could be changed to use i += 100 and it wouldn't make a difference. It's unclear what the author intended here.
  • Doesn't sum the values of i, it only loops over them. No summation is done.
  • range() doesn't include the ending limit (i.e., this example goes up to 9, whereas mathematically, setting $n$ to 10 would include that number)

My advanced math skills are a little rusty, so I needed to check whether the upper limit is included in the summation. While I was researching, I saw several examples that use the Python range() function incorrectly.

Correct code

n = 10
summation = 0
for i in range(n + 1):
  if i != 4:
    summation += i

More efficiently

List comprehensions are more efficient than for loops.

n = 10
summation = sum(i for i in range(n + 1) if i != 4)

Or don't use loops at all for the highest efficiency.

n = 10
summation = sum(filter(lambda i: i != 4, range(n + 1)))

✅ Much better!

Any questions?

Post a comment below.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment