Placement Prep

Sum of Array Elements in Python: Three Approaches

Three ways to sum array elements in Python: built-in sum(), a for loop, and functools.reduce(). Code verified from first principles for CRT placement rounds.

By FACE Prep Team 5 min read
python arrays crt-training placement-prep coding-programs

Python’s built-in sum() solves this in one line, but CRT coding rounds regularly test the manual loop version to check that you understand accumulation, not just function calls.

This article covers all three standard approaches: sum(), a for loop, and functools.reduce(). Each section includes verified outputs and the edge cases that appear in assessment portals used by colleges across Tier-2 and Tier-3 campuses.

What “Array” Means in Python

“Array” in placement question headings almost always means a Python list. Python does have a separate array module (from array import array) that enforces a single element type, and numpy offers its own array type with vectorised operations. But questions labelled “array programs” in CRT test portals use plain lists by default.

This matters because all three approaches below work identically on Python lists, array module objects, and numpy arrays. The syntax for sum() and the for loop does not change between them. If a test prompt explicitly imports array or numpy, only the input construction differs.

The accumulator pattern you will practise here appears in several related CRT programs: the Armstrong number check accumulates the cube of each digit, and the simple calculator program accumulates user-entered values with a running total. Sum of array elements is the cleanest form of the same underlying idea.

Approach 1: The Built-in sum() Function

sum() is the standard tool. It accepts any iterable and an optional start value, then returns the total.

# Sum of array elements using Python's built-in sum()
lst = [1, 2, 3, 4, 5]
total = sum(lst)
print("Sum:", total)
  • Output: Sum: 15
  • Verification: 1 + 2 + 3 + 4 + 5 = 15 ✓

The Python documentation for sum() states that the start value defaults to 0. It also notes that sum() is not intended for string concatenation; use ''.join(iterable) for strings instead.

Edge cases worth knowing

  • Empty list: sum([]) returns 0, no error.
  • Start value: sum([1, 2, 3], 10) returns 16 (list sum is 6, plus start value 10).
  • Negative values: sum([-3, -2, 5]) returns 0. Derivation: -3 + (-2) = -5; -5 + 5 = 0.
  • Float mix: sum([1.5, 2.5, 3.0]) returns 7.0.

Interactive version with user input

# Python program to find sum of array elements with user input
lst = []
n = int(input("Enter the size of the array: "))
print("Enter array elements:")
for _ in range(n):
    lst.append(int(input()))
print("Sum:", sum(lst))

For n = 3 and elements 10, 20, 30, the output is Sum: 60. Verification: 10 + 20 + 30 = 60 ✓

Approach 2: A Manual For Loop

Some test questions say “write a Python program to add array elements without using built-in functions.” The loop version satisfies this constraint and also appears as a sub-problem inside larger CRT tasks.

# Sum of array elements using a for loop
lst = [10, 20, 30, 40, 50]
total = 0
for element in lst:
    total += element
print("Sum:", total)
  • Output: Sum: 150
  • Verification: 10 + 20 = 30; 30 + 30 = 60; 60 + 40 = 100; 100 + 50 = 150 ✓

The loop initialises total at 0 before iterating. Each element is added on its pass. This is the same accumulator pattern that appears in the greatest of two numbers comparison logic and in the digit-cube accumulation of the Armstrong check.

While loop variant

When a test asks you to use index-based access, or when you need to skip alternate elements, a while loop gives the same result with explicit index control:

lst = [10, 20, 30, 40, 50]
total = 0
i = 0
while i < len(lst):
    total += lst[i]
    i += 1
print("Sum:", total)
  • Output: Sum: 150
  • Verification: same derivation as above ✓

Both variants produce 150 for this input. The for loop is more idiomatic Python; the while loop is useful when you need to step by 2, reverse direction, or accumulate only qualifying elements.

Approach 3: functools.reduce()

reduce() applies a two-argument function repeatedly across a sequence, accumulating from left to right. Import it from the standard library’s functools module.

from functools import reduce

lst = [1, 2, 3, 4, 5]
total = reduce(lambda a, b: a + b, lst)
print("Sum:", total)
  • Output: Sum: 15
  • Step-by-step trace:
    • Step 1: f(1, 2) = 3
    • Step 2: f(3, 3) = 6
    • Step 3: f(6, 4) = 10
    • Step 4: f(10, 5) = 15 ✓

The Python documentation for functools.reduce() describes the third argument as initializer. When provided, it is placed before the iterable items in the reduction and serves as the default when the iterable is empty.

Empty-list edge case

Calling reduce() without an initialiser on an empty sequence raises TypeError. The fix is a third argument:

from functools import reduce

# Safe version: initialiser of 0 handles the empty-list case
total = reduce(lambda a, b: a + b, [], 0)
print("Sum:", total)
  • Output: Sum: 0

This edge case appears in test prompts that ask you to handle empty input gracefully.

Which Approach to Use, and When

SituationBest approach
Standard coding round, no constraintsum()
Question says “without built-in functions”Manual for loop
Question asks for functional or higher-order approachfunctools.reduce()
Empty list is valid input and safety is requiredsum() or reduce() with initialiser
Need conditional or partial accumulationManual for loop

For the broader collection of basic Python practice programs, the sum() approach solves the standard form; the for-loop form appears in “no built-in” variants and as a building block inside matrix row-sum and frequency-count problems.

Practise Problems

Work through these before your CRT round:

  • Problem 1: Sum of [7, 14, 21, 28] using all three approaches.
    • Expected output: Sum: 70
    • Verification: 7 + 14 = 21; 21 + 21 = 42; 42 + 28 = 70 ✓
  • Problem 2: Sum of an empty list using sum() and reduce() with initialiser.
    • Both should return 0. sum([]) = 0 ✓; reduce(lambda a, b: a + b, [], 0) = 0 ✓
  • Problem 3: Sum of only even elements in [1, 2, 3, 4, 5, 6].
    • Expected output: 12
    • Verification: 2 + 4 + 6 = 12 ✓
    • Code: sum(x for x in lst if x % 2 == 0)
  • Problem 4: Sum of [-5, 10, -3, 8].
    • Expected output: 10
    • Verification: -5 + 10 = 5; 5 + (-3) = 2; 2 + 8 = 10 ✓

Once the flat-list accumulator clicks, the same pattern extends into 2D matrix row-sums and character-frequency counts, which are the intermediate problems that appear in company-specific assessments after the CRT shortlist.

The reduce() step-by-step trace you just followed is the same computational model behind map-reduce pipelines that LLM applications use for document processing. If working with Python at that layer interests you after placements, TinkerLLM at ₹299 lets you run code against real AI APIs without configuring infrastructure from scratch.

Primary sources

Frequently asked questions

What does sum() return for an empty list in Python?

sum([]) returns 0 by default. The start value is 0 unless you pass a second argument. sum(lst, 10) starts the count from 10 instead of 0.

Can I use sum() on a tuple or a range object?

Yes. Python's sum() works on any iterable: lists, tuples, sets, generators, and range objects all work as long as the elements are numeric.

How do I sum only even elements in a Python list?

Use a generator expression inside sum(): sum(x for x in lst if x % 2 == 0). This filters to even values before summing.

What happens when reduce() is called on an empty list?

reduce(lambda a, b: a + b, []) raises TypeError because there is no initial value. Add a third argument: reduce(lambda a, b: a + b, [], 0) returns 0 safely.

Is a manual for loop faster than sum() in Python?

No. Python's built-in sum() is implemented in C and runs faster than a pure-Python for loop for long lists. For typical placement test inputs the difference is negligible, but sum() is preferred when the question allows it.

How do I find the sum of a 2D array or matrix in Python?

Use sum(sum(row) for row in matrix). The inner sum() returns each row's total; the outer sum() adds all row totals. A nested for loop with one accumulator works equally well.

What if the list contains float values -- does sum() still work?

Yes. sum([1.5, 2.5, 3.0]) returns 7.0. The result type follows Python's numeric rules: integer plus integer gives integer, integer plus float gives float.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF