Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Element-wise Sum

Add corresponding entries of two equal-sized lists. Students use a common index and compare element-wise addition with concatenating the lists themselves.

IntermediatePhase 4 - Level 4: Aggregation & ComparisonExample 7 of 10
element-wise-sum.py
1# Take arrays
2n = int(input("Enter array size: "))
3arr1 = []
4for i in range(n):
5 arr1.append(int(input(f"Array1 element {i+1}: ")))
6
7arr2 = []
8for i in range(n):
9 arr2.append(int(input(f"Array2 element {i+1}: ")))
10
11# Element-wise sum
12sum_arr = []
13for i in range(n):
14 sum_arr.append(arr1[i] + arr2[i])
15
16print(f"Sum array: {sum_arr}")

Output

Enter array size: 3
Array1 element 1: 1
Array1 element 2: 2
Array1 element 3: 3
Array2 element 1: 4
Array2 element 2: 5
Array2 element 3: 6
Sum array: [5, 7, 9]

In this one

  • Pair equal indexes
  • Add values rather than lists
  • Build a result container

How it works

  1. 1

    Read both lists using the same n.

  2. 2

    Append arr1[i] + arr2[i] for each index.

  3. 3

    Print sum_arr after all pairs are processed.

Edge cases

What does n = 0 produce?

What does n = 0 produce?

An empty result list.

Are all pairs of values added?

Are all pairs of values added?

No. Only values at the same index are paired.

What's going on

Both lists are read with the same count n. For every index, arr1[i] + arr2[i] is appended to a new sum_arr.

Thus [1, 2] and [10, 20] produce [11, 22]. Using arr1 + arr2 instead would concatenate lists, not add positions. The source lists stay unchanged, and the result contains one value per shared index.

What does n = 0 produce? An empty result list.

Are all pairs of values added? No. Only values at the same index are paired.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which expression adds corresponding values?

Pick an answer to check it.

Question 2

What does n = 0 produce?

Pick an answer to check it.

Questions people ask

What does n = 0 produce?

An empty result list.

Are all pairs of values added?

No. Only values at the same index are paired.

Which expression adds corresponding values?

arr1[i] + arr2[i].