Sum python for loop

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

Читайте также:  Python open create directory

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

Источник

Sum python for loop

Last updated: Feb 19, 2023
Reading time · 5 min

banner

# Table of Contents

# Sum in a for loop in Python

To sum in a for loop in Python:

  1. Declare a new variable and set it to 0 .
  2. Use a for loop to iterate over a sequence of numbers.
  3. Reassign the variable to its value plus the current number.
Copied!
my_list = [2, 4, 6, 8] total = 0 for num in my_list: total += num print(total) # 👉️ 20

sum in for loop in python

We used a for loop to sum the numbers in a list.

The first step is to declare a new variable and initialize it to 0 .

On each iteration, we use the += operator to reassign the variable to its current value plus the current number.

The following 2 lines of code achieve the same result:

Here is an example that uses the longer reassignment syntax.

Copied!
my_list = [2, 4, 6, 8] total = 0 for num in my_list: total = total + num print(total) # 👉️ 20

using longer reassignment syntax instead

# Sum the numbers in a certain range using a for loop

If you need to add the numbers in a certain range using a for loop, create the range with the range() class.

Copied!
total = 0 for num in range(1, 5): total += num print(total) # 👉️ 10 print(list(range(1, 5))) # 👉️ [1, 2, 3, 4]

sum numbers in range using for loop

The range class is commonly used for looping a specific number of times in for loops and takes the following parameters:

Name Description
start An integer representing the start of the range (defaults to 0 )
stop Go up to, but not including the provided integer
step Range will consist of every N numbers from start to stop (defaults to 1 )

# Sum numbers taken from user input in a for loop

If you need to sum numbers taken from user input in a for loop, use the input() function.

Copied!
# 👇️ user enters 1 2 3 4 user_input = input('Enter space-separated numbers: ') my_list = list(map(int, user_input.split())) print(my_list) # 👉️ [1, 2, 3, 4] total = 0 for num in my_list: total += num print(total) # 👉️ 10

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

Источник

Sum of n numbers in Python using for loop

In this post, you will learn a Python program to find the sum of n numbers using a for loop.

In the given example, we have used the for loop to calculate the sum of n numbers. First, we have taken an int data type number input from the user and stored it in a variable num. Initially, the sum is initialised to 0. Then, we used the for loop for iteration in the range from 1 to num + 1 to increase the number up to the given input. In each iteration, we have added the value to the sum and, at last, printed the sum variable.

Algorithm

  1. Read the input (num) from the user.
  2. Initialize a variable sum with zero.
  3. Use a for loop to iterate from 1 to num.
  4. Inside the loop, add the num to the sum.
  5. At the end, print the value of the sum.

Python Program to find sum of n numbers using for loop

# Sum of natural numbers up to num num = int(input("Please enter the number: ")) sum = 0 for value in range(1, num + 1): sum = sum + value print(sum)
Please enter the number: 20 210

We can see the sum of the number till 20 is 210 as the output.

Please enter the number: 12 78
Please enter the number: 23 276

Источник

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