Python sum all elements 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.

Читайте также:  Python with html and css

Источник

Sum of Elements in the List in Python

How to find the sum of elements in the list in Python? There are different ways to calculate the sum of all the number elements in the list. for example, you can use the sum() built-in function.

Below are the methods to calculate the sum of elements from the list in Python.

  • Method 1: Using Looping like for loop and while loop.
  • Method 2: Using sum() built-in function
  • Method 3: List Comprehension e.t.c

1. Quick Examples of Getting Sum of Elements in a List

Following are quick examples of how to find the sum of elements in the List.

 # Quick Examples of getting sum of elements in list # Consider the list of integers mylist1=[20,40,32,6,78,90] # Using sum() print("SUM: ", sum(mylist1)) # Using sum() start from 50 print("SUM after 50: ", sum(mylist1,50)) # Using List Comprehension with sum() print("SUM: ", sum([i for i in mylist1])) # Using for loop with range total=0 for i in range(len(mylist1)): total=total+mylist1[i] print("SUM: ", total) # Using for loop total=0 for i in mylist1: total=total+i print("SUM: ", total) # Using add() with for loop from operator import add total=0 for i in mylist1: total = add(i, total) print("SUM: ", total) # Using while loop total=0 i=0 while (i < len(mylist1)): total=total+mylist1[i] i=i+1 print("SUM: ", total) 

2. Sum of List Elements in Python using sum()

The sum() is the built-in function in python that is used to get or find the sum of all numeric elements from list. By using this you can also specify an initial value to start the calculating sum.

It takes two parameters as input and returns the total sum of elements in the list. The first parameter is the input list and the second parameter specified the start value in which the sum is computed from this value. This parameter is optional.

Читайте также:  Таблицы html css шаблоны

4.1 sum() Syntax

Let’s see the syntax of sum() function.

 sum(mylist1,start) # Using List Comprehension with sum() sum([iterator for iterator in mylist1] # Using List Comprehension with sum() sum(list(filter(lambda iterator : (iterator ),mylist1))) 

4.2 sum() Parameters

  • mylist1 is the input list
  • start takes the integer value which will start summing from this value.

4.3 Python List sum() Examples

Example 1: Let’s have a list of integers and return the sum of all elements in the list using the python sum() function. Here, we didn’t specify the second parameter. So it used all elements from the list to calculate the sum and the total sum is 266.

 # Consider the list of integers mylist1=[20,40,32,6,78,90] # Using sum() print("SUM: ", sum(mylist1)) # Output: # SUM: 266 

Example 2: Let’s have a list of integers and return the sum of all elements by specifying the initial value.

Here, we specified the start as 10. So, initially the sum = 10, and then it adds each element to get the sum value 266. The final sum is 10+266=276.

And, in the second example, we specified the start as 50. So, initially, the sum = 50, and the sum of elements in the list gets 266. The final sum is 50+266=316.

 # Consider the list of integers mylist1=[20,40,32,6,78,90] # Using sum() start from 10 print("SUM after 10: ", sum(mylist1,10)) # Using sum() start from 50 print("SUM after 50: ", sum(mylist1,50)) # Output: # SUM after 10: 276 # SUM after 50: 316 

3. Using List Comprehension to get Sum of List Elements

Let’s have a list of integers and return the sum of all elements in the list using python sum() by passing List Comprehension as a parameter. With python list comprehension, we can create lists by specifying the elements. We select elements that we want to include, along with any conditions or operations. All this is done in a single line of code. The below example calculates the sum of numbers from the list using comprehension.

 # Consider the list of integers mylist1=[20,40,32,6,78,90] # Using List Comprehension with sum() print("SUM: ", sum([i for i in mylist1])) # Output: # SUM: 266 

We provided for loop inside the list comprehension and iterating each element in the list. So the sum() function will take each value from the list and return the total sum.

3. Find List Sum using for Loop

The for loop in Python is a control flow statement that is used to execute code repeatedly over a sequence like a string , list, tuple , set, range , or dictionary(dict) type.

3.1 for loop with range

Here, we will use range() function in for loop to iterate elements in the python list to get a sum of elements. Inside loop, we will access each element using index position and add each element to the total variable. The sum is stored in this variable. if you wanted to start the initial value, then assign the value you wanted to the total variable.

 # Consider the list of integers mylist1=[20,40,32,6,78,90] # Using for loop with range total=0 for i in range(len(mylist1)): total=total+mylist1[i] print("SUM: ", total) # Output: # SUM: 266 

3.2 for loop

Here, we just use the list without range() function. Here, we will get a value from the list for each iteration and add each element to the variable. The sum is stored in this variable.

 # Consider the list of integers mylist1=[20,40,32,6,78,90] # Using for loop total=0 for i in mylist1: total=total+i print("SUM: ", total) # Output: # SUM: 266 

3.3 for loop with add()

The add() method is available in the operator module which will add elements from the list to get a sum of elements. It takes two variables as parameters.

Читайте также:  Php mbstring extension установка

So we can specify this method and pass the iterator as the first parameter and total variable as the second parameter. On iteration second parameter will update and store in result again.

 from operator import add # Consider the list of integers mylist1=[20,40,32,6,78,90] # Using add() with for loop total=0 for i in mylist1: total = add(i, total) print("SUM: ", total) # Output: # SUM: 266 

4. Find List Sum using while Loop

Inside the while loop, we will access each element using the index position and add each element to the total variable. The sum is stored in this variable. Each time we need to increment the iterator till it is less than the length of the list.

Let’s create a list of integers and return the total sum using a while loop.

 # Consider the list of integers mylist1=[20,40,32,6,78,90] # Using while loop total=0 i=0 while (i < len(mylist1)): total=total+mylist1[i] i=i+1 print("SUM: ", total) # Output: # SUM: 266 

5. Conclusion

In this article, you have learned different ways to find the sum of list elements in Python. We used for loop to find the sum of all elements present in the list. Next, we saw how to use a while loop to find the sum of elements in the list. After that, we used sum() method to return the total sum of elements directly in the list. It can also be possible to pass the list comprehension as a parameter to this function to return the total sum.

You may also like reading:

Источник

Подсчет количества и суммы элементов в массиве 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

Источник

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