Open In App

Python | Element indices Summation

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Usually, we require to find the sum of index, in which the particular value is located. There are many method to achieve that, using index() etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in list. Lets discuss certain ways to do so.

Method #1 : Naive Method + sum() We can achieve this task by iterating through the list and check for that value and just append the value index in new list and print that. This is the basic brute force method to achieve this task. The sum() is used to perform sum of list. 

Python3




# Python code to demonstrate
# Element indices Summation
# using naive method + sum()
 
# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print ("Original list : " + str(test_list))
 
# using naive method
# Element indices Summation
# to find indices for 3
res_list = []
for i in range(0, len(test_list)) :
    if test_list[i] == 3 :
        res_list.append(i)
res = sum(res_list)
 
# printing resultant list
print ("New indices summation : " + str(res))


Output : 

Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

Time complexity: O(n) where n is the length of the test_list. The code uses a for loop to traverse the list and perform the necessary operation
Auxiliary space: O(m), where m is the number of occurrences of the element being searched in the list. This is because the space complexity is determined by the size of the res_list, which grows as the number of occurrences of the element being searched increases.

Method #2: Using list comprehension + sum() List comprehension is just the shorthand technique to achieve the brute force task, just uses lesser lines of codes to achieve the task and hence saves programmers time. The sum() is used to perform sum of list. 

Python3




# Python code to demonstrate
# Element indices Summation
# using list comprehension + sum()
 
# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print ("Original list : " + str(test_list))
 
# using list comprehension + sum()
# Element indices Summation
# to find indices for 3
res_list = [i for i in range(len(test_list)) if test_list[i] == 3]
res = sum(res_list)
 
# printing resultant list
print ("New indices summation : " + str(res))


Output : 

Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

Time complexity: O(n), where n is the length of the input list ‘test_list’, because the program loops over the input list once to find the indices of the elements equal to 3, and the length of the list is n.
Auxiliary space: O(m), where m is the number of indices where the element is 3. This is because the program creates a new list ‘res_list’ containing these indices, and the size of this list is proportional to the number of occurrences of the element 3 in the input list.

Method#3: Using reduce and lambda function With these function we can perform this task. We can use reduce to iterate over the list range and with lambda function checks if element is define value or not if then we add result with index of element else leave result. 

Python3




# Python code to demonstrate
# Element indices Summation
# using reduce + lambda function
from  functools import reduce
# initializing list
Tlist = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print ("Original list : " + str(Tlist))
 
# using reduce + lambda
# Element indices Summation
# to find indices for 3
rang = len(Tlist)
res = reduce(lambda x, y : x + y if (Tlist[y] == 3) else x, range(rang), 0 )
 
# printing resultant list
print ("New indices summation : " + str(res))


Output:

Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary space: O(m), where m is the number of indices

Method #4: Using for loop, without sum()

Python3




# Python code to demonstrate
# Element indices Summation
 
# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print ("Original list : " + str(test_list))
 
# using naive method
# Element indices Summation
# to find indices for 3
res=0
for i in range(0, len(test_list)) :
    if test_list[i] == 3 :
        res+=i
 
 
# printing resultant list
print ("New indices summation : " + str(res))


Output

Original list : [1, 3, 4, 3, 6, 7]
New indices summation : 4

Method 5: Using numpy

  • Convert the list to a numpy array:
    The first step is to convert the original list to a numpy array using the np.array() function. This allows us to use numpy functions to manipulate the data.
  • Use the where() function to find the indices of the element:
    Next, we use the np.where() function to find the indices where the target element (in this case, 3) occurs in the numpy array. The where() function returns a tuple of arrays, one for each dimension of the input array. Since we’re working with a 1-dimensional array, we only need the first element of the tuple, which contains the indices.
  • Sum the indices:
    We then use the np.sum() function to sum the indices where the element occurs. This gives us the desired result.

Python3




import numpy as np
 
# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print("Original list: " + str(test_list))
 
# using numpy where function
# Convert the list to a numpy array
arr = np.array(test_list)
 
# Use the where function to get the indices where the element occurs
indices = np.where(arr == 3)[0]
 
# Sum the indices using numpy sum function
res = np.sum(indices)
 
# printing resultant list
print("New indices summation: " + str(res))


Output:

Original list: [1, 3, 4, 3, 6, 7]
New indices summation: 4

Time Complexity: O(n + m)

  • Converting the list to a numpy array takes O(n) time, where n is the length of the list.
  • The np.where() function takes O(n) time to find the indices where the target element occurs in the numpy array.
  • The np.sum() function takes O(m) time to sum the indices, where m is the number of indices returned by np.where().
  • Therefore, the overall time complexity of the numpy approach is O(n + m).

Auxiliary Space: O(n + m)

  • Converting the list to a numpy array requires O(n) auxiliary space to store the numpy array.
  • The np.where() function returns an array of indices, which requires O(m) auxiliary space to store.
  • The np.sum() function requires constant auxiliary space.
  • Therefore, the overall auxiliary space complexity of the numpy approach is O(n + m).

Method #6: Using enumerate and for loop, without sum()

Use enumerate and a for loop to iterate over the list and calculate the sum of indices where the element occurs

Python3




# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print("Original list: " + str(test_list))
 
# using enumerate and for loop to get the indices
indices_sum = 0
for i, x in enumerate(test_list):
    if x == 3:
        indices_sum += i
 
# printing resultant sum
print("New indices summation: " + str(indices_sum))


Output

Original list: [1, 3, 4, 3, 6, 7]
New indices summation: 4

Time complexity: O(n) because it iterates over the entire list once. 
Auxiliary space: O(1) because it only uses a constant amount of extra memory to store the sum of indices.

Method #7: Using itertools:

Algorithm :

  1. Initialize the input list test_list with some values.
  2. Initialize a variable res to 0.
  3. Use the enumerate() function from the itertools module to create an iterator that yields pairs of (index, value) tuples for each element in the list.
  4. Use a generator expression with the sum() function to calculate the sum of the indices where the value is equal to 3.
  5. Print the sum value res.

Python3




import itertools
# initializing list
test_list = [1, 3, 4, 3, 6, 7]
# printing initial list
print("Original list: " + str(test_list))
res = sum(idx for idx, val in enumerate(test_list) if val == 3)
# printing resultant list
print("New indices summation: " + str(res))
#This code is contributed by Jyothi pinjala.


Output

Original list: [1, 3, 4, 3, 6, 7]
New indices summation: 4

The time complexity : O(N), where N is the length of the input list. This is because we need to iterate over the entire list once to check each element and its index.

The auxiliary space :O(1), as we are only using a constant amount of extra memory to store the index sum.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads