Питон сложить все элементы массива

How to Find the Sum of Elements in a List in Python

In Python, programmers work with a lot of lists. Sometimes, it is necessary to find out the sum of the elements of the lists for other operations within the program.

In this article, we will take a look at the following ways to calculate sum of all elements in a Python list:

1) Using sum() Method

Python provides an inbuilt function called sum() which sums up the numbers in a list.

Syntax

  • Iterable – It can be a list, a tuple or a dictionary. Items of the iterable have to be numbers.
  • Start – This number is added to the resultant sum of items. The default value is 0.

The method adds the start and the iterable elements from left to right.

Example:

Code Example:

# Python code to explain working on sum() method # Declare list of numbers numlist = [2,4,2,5,7,9,23,4,5] numsum = sum(numlist) print('Sum of List: ',numsum) # Example with start numsum = sum(numlist, 5) print('Sum of List: ',numsum)

Output:

Sum of List: 61 Sum of List: 66

Explanation

Here, you can see that the sum() method takes two parameters – numlist, the iterable and 5 as the start value. The final value is 61 (without the start value) and 66 (with the start value 5 added to it).

Читайте также:  Какие существуют java платформы

2) Using for Loop

# Python code to calculate sum of integer list # Using for loop # Declare list of numbers numlist = [2,4,2,5,7,9,23,4,5] # Calculate sum of list numsum=0 for i in numlist: numsum+=i print('Sum of List: ',numsum)

Output

Explanation

Here, a for loop is run over the list called numlist. With each iteration, the elements of the list are added. The result is 61 which is printed using the print statement.

3) Sum of List Containing String Value

# Python code to calculate sum of list containing integer as string # Using for loop # Declare list of numbers as string numlist = ['2','4','2','5','7','9','23','4','5'] # Calculate sum of list numsum=0 for i in numlist: numsum+=int(i) print('Sum of List: ',numsum)

Output

Here, the list called numlist contains integers as strings. Inside the for loop, these string elements are added together after converting them into integers, using the int() method.

4) Using While Loop

# Python code to calculate sum of list containing integer as string # Using While loop # Declare list of numbers as string numlist = [2,4,2,5,7,9,23,4,5] # Declare function to calculate sum of given list def listsum(numlist): total = 0 i = 0 while i < len(numlist): total = total + numlist[i] i = i + 1 return total # Call Function # Print sum of list totalsum = listsum(numlist); print('Sum of List: ', totalsum)

Explanation

In this program, elements of the numlist array are added using a while loop. The loop runs until the variable i is less than the length of the numlist array. The final summation is printed using the value assigned in the totalsum variable.

Conclusion

Using a for loop or while loop is great for summing elements of a list. But the sum() method is faster when you are handling huge lists of elements.

  • Python Training Tutorials for Beginners
  • Square Root in Python
  • Python Factorial
  • Python Continue Statement
  • Armstrong Number in Python
  • Python map()
  • Python String find
  • Python String Contains
  • Python eval
  • Python zip()
  • Python Range
  • Python IDE
  • Python Print Without Newline
  • Python Split()
  • Bubble Sort in Python
  • Attribute Error Python
  • Python Combine Lists
  • Convert List to String Python
  • Compare Two Lists in Python
  • Python KeyError

Источник

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

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

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

Использование встроенной функции sum()

Самый простой и прямой способ подсчета суммы всех элементов списка — использовать встроенную функцию sum() .

list1 = [1, 2, 3, 4, 5] print(sum(list1)) #15

Использование функции sum() с аргументом start

Функция sum() также принимает второй аргумент, start , который добавляется к общей сумме.

list1 = [1, 2, 3, 4, 5] print(sum(list1, 10)) #25

Использование цикла for для подсчета суммы

Если вы не хотите или не можете использовать функцию sum() , вы можете подсчитать сумму элементов списка, используя цикл for .

list1 = [1, 2, 3, 4, 5] total = 0 for i in list1: total += i print(total) #15

Использование функции reduce()

Функция reduce() из модуля functools применяет заданную функцию к элементам списка последовательно таким образом, что результат одного вызова функции используется в следующем вызове. Это можно использовать для подсчета суммы элементов списка.

from functools import reduce import operator list1 = [1, 2, 3, 4, 5] total = reduce(operator.add, list1) print(total) #15

Использование генератора списков

Вы можете использовать генератор списков для вычисления суммы элементов списка, особенно если вы хотите применить какую-то функцию к каждому элементу перед суммированием.

list1 = [1, 2, 3, 4, 5] total = sum(i**2 for i in list1) print(total) #55

В этом примере мы вычисляем сумму квадратов всех элементов списка.

Сумма элементов во вложенных списках

Если у вас есть список списков и вы хотите подсчитать сумму всех элементов всех списков, вы можете использовать вложенный цикл for .

list1 = [[1, 2, 3], [4, 5],[6, 7, 8, 9]] total = 0 for sublist in list1: total += sum(sublist) print(total) #45

В этом примере внешний цикл for проходит через каждый подсписок, а внутренний вызов sum() суммирует элементы каждого подсписка.

Использование генераторов списков для суммирования элементов во вложенных списках

Вы также можете использовать генераторы списков для подсчета суммы элементов во вложенных списках, особенно если вы хотите применить какую-то функцию к каждому элементу перед суммированием.

list1 = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] total = sum(i for sublist in list1 for i in sublist) print(total) #45

В этом примере генератор списка i for sublist in list1 for i in sublist генерирует все элементы всех подсписков, а функция sum() суммирует их.

Заключение

Существует множество способов подсчета суммы элементов списка в Python, от простого использования функции sum() до более сложных подходов, таких как использование функции reduce() или генераторов списков. В зависимости от ваших потребностей и предпочтений, вы можете выбрать тот подход, который наиболее подходит для вашей задачи.

Разбиваем строку на символы в Python: основные методы и примеры

Разбиваем строку на символы в Python: основные методы и примеры

Функция breakpoint() в Python: принцип работы и примеры отладки кода

Функция breakpoint() в Python: принцип работы и примеры отладки кода

Работаем с пустыми списками в Python

Работаем с пустыми списками в Python

Руководство по импорту функций в Python: примеры и методы

Руководство по импорту функций в Python: примеры и методы

Метод isascii() в Python: как проверить, что строка содержит только ASCII символы

Метод isascii() в Python: как проверить, что строка содержит только ASCII символы

Использование функции id() в Python: примеры и описание

Использование функции id() в Python: примеры и описание

Источник

Оцените статью