Как найти сумму индексов массива python

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

test_list = [1, 3, 4, 3, 6, 7]

print ("Original list : " + str(test_list))

res_list = []

for i in range(0, len(test_list)) :

    if test_list[i] == 3 :

        res_list.append(i)

res = sum(res_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

test_list = [1, 3, 4, 3, 6, 7]

print ("Original list : " + str(test_list))

res_list = [i for i in range(len(test_list)) if test_list[i] == 3]

res = sum(res_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

from  functools import reduce

Tlist = [1, 3, 4, 3, 6, 7]

print ("Original list : " + str(Tlist))

rang = len(Tlist)

res = reduce(lambda x, y : x + y if (Tlist[y] == 3) else x, range(rang), 0 )

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

test_list = [1, 3, 4, 3, 6, 7]

print ("Original list : " + str(test_list))

res=0

for i in range(0, len(test_list)) :

    if test_list[i] == 3 :

        res+=i

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

test_list = [1, 3, 4, 3, 6, 7]

print("Original list: " + str(test_list))

arr = np.array(test_list)

indices = np.where(arr == 3)[0]

res = np.sum(indices)

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

test_list = [1, 3, 4, 3, 6, 7]

print("Original list: " + str(test_list))

indices_sum = 0

for i, x in enumerate(test_list):

    if x == 3:

        indices_sum += i

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

test_list = [1, 3, 4, 3, 6, 7]

print("Original list: " + str(test_list))

res = sum(idx for idx, val in enumerate(test_list) if val == 3)

print("New indices summation: " + str(res))

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.

Last Updated :
28 Mar, 2023

Like Article

Save Article

A simple way is to use the iter_tools permutation

# If you are given a list

numList = [1,2,3,4,5,6,7]

# and you are asked to find the number of three sums that add to a particular number

target = 10
# How you could come up with the answer?

from itertools import permutations

good_permutations = []

for p in permutations(numList, 3):
    if sum(p) == target:
        good_permutations.append(p)

print(good_permutations)

The result is:

[(1, 2, 7), (1, 3, 6), (1, 4, 5), (1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 1, 7), (2, 3, 
5), (2, 5, 3), (2, 7, 1), (3, 1, 6), (3, 2, 5), (3, 5, 2), (3, 6, 1), (4, 1, 5), (4, 
5, 1), (5, 1, 4), (5, 2, 3), (5, 3, 2), (5, 4, 1), (6, 1, 3), (6, 3, 1), (7, 1, 2), 
(7, 2, 1)]

Note that order matters — meaning 1, 2, 7 is also shown as 2, 1, 7 and 7, 1, 2. You can reduce this by using a set.

To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies.

Method 1: Naive method This is the most generic method that can be possibly employed to perform this task of accessing the index along with the value of the list elements. This is done using a loop. The task of performing sum is performed using external variable to add. 

Python3

test_list = [1, 4, 5, 6, 7]

print ("The original list is : " + str(test_list))

res = []

for i in range(len(test_list)):

    res.append(i + test_list[i])

print ("The list index-value summation is : " + str(res))

Output : 

The original list is : [1, 4, 5, 6, 7]
The list index-value summation is : [1, 5, 7, 9, 11]

Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.

Method 2: Using list comprehension + sum() This method works in similar way as the above method but uses the list comprehension technique for the same, this reduces the possible lines of code to be written and hence saves time. The task of performing summation is done by sum(). 

Python3

test_list = [1, 4, 5, 6, 7]

print ("The original list is : " + str(test_list))

res = [sum(list((i, test_list[i]))) for i in range(len(test_list))]

print ("The list index-value summation is : " + str(res))

Output : 

The original list is : [1, 4, 5, 6, 7]
The list index-value summation is : [1, 5, 7, 9, 11]

Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.

Method 3:  Using Enumerate
This method uses the built-in enumerate() method which is used to loop over a list along with the index of the elements present in it.

Python3

test_list = [1, 4, 5, 6, 7]

print ("The original list is : " + str(test_list))

res = [index + value for index, value in enumerate(test_list)]

print ("The list index-value summation is : " + str(res))

Output

The original list is : [1, 4, 5, 6, 7]
The list index-value summation is : [1, 5, 7, 9, 11]

Time complexity: O(n)
Auxiliary Space: O(n)

Method 4 : Using map() and lambda function:

  • The enumerate() function is used to generate a sequence of tuples (index, value) for each element in test_list.
  • The map() function is used to apply a lambda function to each tuple in the sequence.
  • The lambda function adds the index and value of each tuple together, which creates a new sequence of integers.
  • The list() function is used to convert the sequence of integers to a new list res.
  • The print() function is used to display the resulting list res to the user.

Python3

test_list = [1, 4, 5, 6, 7]

res = list(map(lambda x: x[0]+x[1], enumerate(test_list)))

print("The list index-value summation is : " + str(res))

Output

The list index-value summation is : [1, 5, 7, 9, 11]

Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), as we create a new list res that contains the same number of elements as the input list. 

Last Updated :
09 Apr, 2023

Like Article

Save Article

Lists are very commonly used to store sequences of values (for example, numbers) in Python. When working with lists, it can be handy to know how to quickly get the sum of values in a list. For example, you have a list of your recorded footsteps in the last seven days and you want to know the total sum. In this tutorial, we will look at how to get the sum of the elements in a list in Python with the help of some examples.

How to get the sum of a list of numbers in Python?

sum of elements in a python list

You can use the python built-in sum() function to get the sum of list elements. Alternatively, you can use a loop to iterate through the list items and use a variable to keep track of the sum.

Let’s look at the above-mentioned methods with the help of some examples.

Using sum() to get the total in a list

The built-in sum() function in Python is used to return the sum of an iterable. To get the sum total of a list of numbers, you can pass the list as an argument to the sum() function.

# create a list
ls = [10, 15, 20, 25]
# sum of list elements
sum(ls)

Output:

70

We get the sum of the values in the list as a scaler value.

Note that the sum() function may result in loss of precision with extended sums of floating-point numbers. For example –

# create a list
ls = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
# sum of list elements
sum(ls)

Output:

0.8999999999999999

As an alternative, you can use the math standard library’s fsum() function to get an accurate sum of floating-point numbers and prevent loss of precision.

import math

# create a list
ls = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
# sum of list elements
math.fsum(ls)

Output:

0.9

We get the accurate result this time. For more on the fsum() function, refer to its documentation.

Using loop to get the sum

Alternatively, you can use the straightforward method of iterating through the list elements and keeping track of the sum.

# create a list
ls = [10, 15, 20, 25]
# use a loop to get the sum
total = 0
for item in ls:
    total += item
print(total)

Output:

70

We get the sum of the values in the list.

You might also be interested in –

  • Python – Find Average of values in a List
  • Python – Get median of a List
  • Find Mode of List in Python

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

Списки Python – одна из наиболее часто используемых структур данных. Часто приходится выполнять различные операции со списками. В этой статье обсудим способы нахождения суммы элементов в списке в Python.

@python_job_interview – в нашем канале разобраны все возможные практические задачи Python

Находим сумму элементов в списке с помощью цикла For

Первый способ найти сумму элементов в списке – это выполнить итерацию по списку и добавить каждый элемент с помощью цикла for. Сначала рассчитаем длину списка с помощью метода len(). После этого объявим переменную sumOfElements равной 0. Затем используем функцию range(), чтобы создать последовательность чисел от 0 до (длина list-1). Используя числа в этой последовательности, мы получим доступ к элементам данного списка и добавим их в sumOfElements:

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
list_length=len(myList)
sumOfElements=0
for i in range(list_length):
    sumOfElements=sumOfElements+myList[i]

print("Sum of all the elements in the list is:", sumOfElements)

Вывод:

The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45

Также можно напрямую перебирать список, используя цикл for. Так мы получим прямой доступ к каждому элементу в списке и добавим их в сумму элементов:

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
sumOfElements = 0
for element in myList:
    sumOfElements = sumOfElements + element

print("Sum of all the elements in the list is:", sumOfElements)

Вывод:

The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45

Находим сумму элементов в списке с помощью цикла While

Также можно использовать цикл while, чтобы найти сумму элементов в списке. Для этого сначала рассчитаем длину списка с помощью метода len(). После этого инициализируем переменные с именами count и sumOfElements. Мы инициализируем оба элемента равными 0.

С помощью цикла while мы получим доступ к каждому элементу списка с помощью переменной count и добавим их в sumOfElements. После этого мы увеличим значение count на 1 и продолжим до тех пор, пока количество не станет равным длине списка.

Ваша программа может выглядеть так:

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
list_length = len(myList)
sumOfElements = 0
count = 0
while count < list_length:
    sumOfElements = sumOfElements + myList[count]
    count = count + 1

print("Sum of all the elements in the list is:", sumOfElements)

Вывод:

The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45

Сумма элементов в списке с помощью функции sum()

Также Python предоставляет нам встроенную функцию sum() для вычисления суммы элементов в любом объекте коллекции. Функция sum() принимает повторяющийся объект, такой как список, кортеж или набор, и возвращает сумму элементов в объекте.

Так можно найти сумму элементов списка с помощью функции sum():

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
sumOfElements = sum(myList)
print("Sum of all the elements in the list is:", sumOfElements)

Вывод:

The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45

Заключение

В этой статье мы обсудили различные способы, как найти суммы элементов в списке Python.

Просмотры: 37 231

Понравилась статья? Поделить с друзьями:
  • Как найти вероятность в задаче огэ
  • Как найти свои пенсионные накопления в негосударственном
  • Как найти график линейной функции 7 класс
  • Как составить цену на кресло
  • Как составить план по картине грачи прилетели