Open In App

Element indices Summation - Python

Last Updated : 30 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Our task is to calculate the sum of elements at specific indices in a list. This means selecting elements at specific positions and computing their sum. Given a list and a set of indices, the goal is to compute the sum of elements present at those indices. For example, given the list [10, 20, 30, 40, 50] and indices [1, 3], the output should be 20 + 40 = 60. Let’s explore different methods to achieve this.

Using List Comprehension with Sum

This method is the most efficient due to its use of a generator expression, avoiding unnecessary list creation.

Python
# Input list and indices
arr = [10, 20, 30, 40, 50]
indices = [1, 3]

# Compute sum of elements at given indices
result = sum(arr[i] for i in indices)
print("Sum of elements at given indices:", result)

Output
Sum of elements at given indices: 60

Explanation:

  • The list comprehension [arr[i] for i in indices] extracts elements at the given indices.
  • The sum() function calculates their total sum efficiently..

Let's explore some more ways to perform element indices summation in Python.

Using map() and Sum

This method uses functional programming by applying map with arr.__getitem__.

Python
arr = [10, 20, 30, 40, 50]
indices = [1, 3]

# Compute sum using map
result = sum(map(arr.__getitem__, indices))
print("Sum of elements at given indices:", result)

Output
Sum of elements at given indices: 60

Explanation:

  • arr.__getitem__ is used to fetch elements at the specified indices.
  • map() applies this function to all indices, and sum computes the total sum.

Using NumPy for Large Lists

For handling large numerical lists efficiently, NumPy is a great choice.

Python
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
indices = np.array([1, 3])

# Compute sum
result = np.sum(arr[indices])
print("Sum of elements at given indices:", result)

Output
Sum of elements at given indices: 60

Explanation:

  • The arr[indices] operation selects elements from arr at positions specified in indices, i.e., arr[1] (20) and arr[3] (40).
  • np.sum(arr[indices]) efficiently computes the sum of selected elements (20 + 40 = 60) using optimized NumPy operations.

Using for loop

This method manually sums elements by iterating over indices using a for loop.

Python
arr = [10, 20, 30, 40, 50]
indices = [1, 3]

# Initialize sum variable
total = 0

# Iterate through indices and sum corresponding elements
for i in indices:
    total += arr[i]
print("Sum of elements at given indices:", total)

Output
Sum of elements at given indices: 60

Explanation:

  • A total variable is initialized to store the sum.
  • A loop iterates through the indices list and adds the corresponding elements from arr.

Next Article
Practice Tags :

Similar Reads