How To Calculate the Sum of 1 to 100 in Python with One Line of Code?

In Python coding interviews, efficiency and code simplicity are crucial. The problem here requires calculating the sum of integers from 1 to 100 using just one line of code. This means we need to leverage Python’s built-in functions to achieve the goal in the most concise manner.

1. The Traditional Approach: Using a Loop.

Before optimizing, let’s consider the most common way of summing numbers:

total = 0
for i in range(1, 101):
    total += i
print(total)

This approach is valid, but it consists of multiple lines and a loop, making it less efficient.

2. Using `range()` to Generate a Sequence.

Python provides the `range()` function, which generates a sequence of numbers. To create a sequence from 1 to 100, we use:

numbers = range(1, 101)

Here, `numbers` contains all integers from 1 to 100.

3. Using `sum()` for Efficient Summation.

Python has a built-in function `sum()` that quickly sums up elements in an iterable:

total = sum(range(1, 101))
print(total)

This method eliminates the need for a loop and provides a much cleaner solution.

4. The One-Line Solution.

By combining the two functions, we arrive at the ultimate one-liner:

print(sum(range(1, 101)))

This single line of code does the following:

  1. Generates a sequence of numbers from 1 to 100 using `range(1, 101)`.
  2. Computes their sum using `sum()`.
  3. Prints the result with `print()`.

5. Why is This the Best Approach?

  1. Concise: Achieves the task in just one line.
  2. Efficient: `sum()` is implemented in C, making it significantly faster than manual loops.
  3. Readable: The code is self-explanatory and easy to understand.

6. Conclusion.

The best way to compute the sum of integers from 1 to 100 in Python is to use `sum(range(1, 101))`. This method is efficient, elegant, and aligns with Python’s philosophy of simplicity and readability. Next time you encounter such a problem, remember this one-liner for an optimized solution.

7. Demo Video.

You can watch the following demo video by select the subtitle to your preferred subtitle language.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top