Python sum element in array

Python Program to Find Sum of All Array Elements

Sum of array elements in python; Through this tutorial, you will learn how to sum of all array elements in a python program.

Python Program to Find Sum of All Array Elements

  • Python Program to find Sum of Elements in a List using sum function
  • Program to find Sum of Elements in a List without using for loop
  • Program to find Sum of Elements in a List without using while loop
  • Python Program to Calculate Sum of all Elements in a List using Functions

Python Program to find Sum of Elements in a List Using sum function

# Python Program to find Sum of all Elements in a List using sum function NumList = [] Number = int(input("Please enter the Total Number of List Elements : ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) total = sum(NumList) print("\n The Sum of All Element in this List is : ", total)

After executing the program, the output will be:

Please enter the Total Number of List Elements : 5 Please enter the Value of 1 Element : 10 Please enter the Value of 2 Element : 56 Please enter the Value of 3 Element : 5 Please enter the Value of 4 Element : 44 Please enter the Value of 5 Element : 57 The Sum of All Element in this List is : 172

Program to find Sum of Elements in a List without using for loop

# Python Program to find Sum of all Elements in a List using for loop NumList = [] total = 0 Number = int(input("Please enter the Total Number of List Elements : ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) for j in range(Number): total = total + NumList[j] print("\n The Sum of All Element in this List is : ", total)

After executing the program, the output will be:

Please enter the Total Number of List Elements : 4 Please enter the Value of 1 Element : 10 Please enter the Value of 2 Element : 20 Please enter the Value of 3 Element : 30 Please enter the Value of 4 Element : 40 The Sum of All Element in this List is : 100

Python Program to Calculate Sum of Elements in a List using While loop

# Python Program to find Sum of all Elements in a List using while loop NumList = [] total = 0 j = 0 Number = int(input("Please enter the Total Number of List Elements : ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) while(j < Number): total = total + NumList[j] j = j + 1 print("\n The Sum of All Element in this List is : ", total)

After executing the program, the output will be:

Please enter the Total Number of List Elements : 3 Please enter the Value of 1 Element : 1 Please enter the Value of 2 Element : 2 Please enter the Value of 3 Element : 3 The Sum of All Element in this List is : 6

Python Program to Calculate Sum of all Elements in a List using Functions

# Python Program to find Sum of all Elements in a List using function def sum_of_list(NumList): total = 0 for j in range(Number): total = total + NumList[j] return total NumList = [] Number = int(input("Please enter the Total Number of List Elements : ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of %d Element : " %i)) NumList.append(value) total = sum_of_list(NumList) print("\n The Sum of All Element in this List is : ", total)

After executing the program, the output will be:

Please enter the Total Number of List Elements : 5 Please enter the Value of 1 Element : 5 Please enter the Value of 2 Element : 10 Please enter the Value of 3 Element : 52 Please enter the Value of 4 Element : 53 Please enter the Value of 5 Element : 88 The Sum of All Element in this List is : 208

Author Admin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Читайте также:  Test java web application

Источник

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).

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.

  • Learn Python Programming
  • Python vs PHP
  • pip is not recognized
  • Python Min()
  • Python Continue Statement
  • Python map()
  • Inheritance in Python
  • Python New 3.6 Features
  • Python eval
  • Python Range
  • Python String Title() Method
  • String Index Out of Range Python
  • Python Print Without Newline
  • Id() function in Python
  • Python Split()
  • Convert List to String Python
  • Remove Punctuation Python
  • Compare Two Lists in Python
  • Python Infinity
  • Python Return Outside Function

Источник

Подсчет количества и суммы элементов в массиве Python

В этой программе нам нужно подсчитать и вывести на печать количество элементов, присутствующих в массиве Python, и вычислить их сумму.

Подсчет всех элементов массива

Некоторые элементы, присутствующие в массиве, можно найти, вычислив длину массива.

Программа Python для печати количества элементов, присутствующих в массиве

Длина приведенного выше массива равна 5. Следовательно, количество элементов, присутствующих в массиве, равно 5.

Алгоритм

  • ШАГ 1: Объявите и инициализируйте массив.
  • ШАГ 2: Рассчитайте длину массива, которая представляет собой количество элементов, присутствующих в массиве.
  • ШАГ 3: Встроенная функция может вычислить длину.
  • ШАГ 4: Наконец, напечатайте длину массива.

Массив в Python объявляется как:

Имя массива = [ele1, ele2, ele3,….]

Метод len() возвращает длину массива в Python.

Программа

#Initialize array arr = [1, 2, 3, 4, 5]; #Number of elements present in an array can be found using len() print("Number of elements present in given array: " + str(len(arr)));
Number of elements present in given array: 5

Вычисление суммы элементов массива

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

Программа Python для печати суммы всех элементов в массиве

Сумма всех элементов массива равна 1 + 2 + 3 + 4 + 5 = 15.

Алгоритм

  • ШАГ 1: Объявите и инициализируйте массив.
  • ШАГ 2: Сумма переменных будет использоваться для вычисления суммы элементов. Инициализируйте его на 0.
  • ШАГ 3: Прокрутите массив и добавьте каждый элемент массива в переменную sum как sum = sum + arr[i].

Программа

#Initialize array arr = [1, 2, 3, 4, 5]; sum = 0; #Loop through the array to calculate sum of elements for i in range(0, len(arr)): sum = sum + arr[i]; print("Sum of all the elements of an array: " + str(sum));
Sum of all the elements of an array: 15

Источник

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