 jubayer-hossain
8/18/2018 - 5:52 PM

## How To find the sum of all the elements in a list.

How To find the sum of all the elements in a list.

## To find the sum of all the elements in a list.

1. Read input number asking for length of the list using input()
2. Initialise an empty list lst = [].
3. Read each number using a for loop.
4. In the for loop append each number to the list.
5. Now we use predefined function sum() to find the sum of all the elements in a list.
6. Print the result.

### By Using Buil-in Function sum()

``````li = []
n = int(input("Enter the number of elements: "))
for i in range(n):
elem = int(input("Enter the elements: "))
li.append(elem)
print("The list:",li)
print("The sum of the list = {}".format(sum(li)))
``````

### Test Case-1

``````li = []
n = int(input("Enter the number of elements: "))
for i in range(n):
elem = int(input("Enter the elements: "))
li.append(elem)
print("The list:",li)
print("The sum of the list = {}".format(sum(li)))
``````
``````Enter the number of elements: 4
Enter the elements: 30
Enter the elements: 30
Enter the elements: 30
Enter the elements: 30
The list: [30, 30, 30, 30]
The sum of the list = 120
``````

### Test Case-2

``````
li = []
n = int(input("Enter the number of elements: "))
for i in range(n):
elem = int(input("Enter the elements: "))
li.append(elem)
print("The list:",li)
print("The sum of the list = {}".format(sum(li)))
``````
``````Enter the number of elements: 10
Enter the elements: 4
Enter the elements: 5
Enter the elements: -10
Enter the elements: 20
Enter the elements: -50
Enter the elements: 30
Enter the elements: -9
Enter the elements: -2
Enter the elements: 0
Enter the elements: 7
The list: [4, 5, -10, 20, -50, 30, -9, -2, 0, 7]
The sum of the list = -5
``````

## Without Built-in Function Finding Sum

### Source Code

``````numbers = []
n = int(input("Enter the elements: "))
for i in range(0, n):
elem = int(input("Enter the elements: "))
numbers.append(elem)

def findSum(numbers):
total = 0
for j in numbers:
total += j

if __name__ == '__main__':
temp = findSum(numbers)
print("The created list: ",numbers)
print("The Sum = ",temp)
``````

### Test Case-1

``````numbers = []
n = int(input("Enter the elements: "))
for i in range(0, n):
elem = int(input("Enter the elements: "))
numbers.append(elem)

def findSum(numbers):
total = 0
for j in numbers:
total += j

if __name__ == '__main__':
temp = findSum(numbers)
print("The created list: ",numbers)
print("The Sum = ",temp)

``````
``````Enter the elements: 4
Enter the elements: 30
Enter the elements: 40
Enter the elements: 10
Enter the elements: 20
The created list:  [30, 40, 10, 20]
The Sum =  100
``````
``````numbers = []
n = int(input("Enter the elements: "))
for i in range(0, n):
elem = int(input("Enter the elements: "))
numbers.append(elem)

def findSum(numbers):
total = 0
for j in numbers:
total += j