user14887535
user14887535

Reputation: 23

How a Python code to store integer in list and then find the sum of integer stored in the List

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list

lst = list( input("Enter the list of items :") )  
sum_element = 0
for i in lst:
    sum_element = sum_element+int(i)
print(sum_element)

Upvotes: 0

Views: 754

Answers (2)

Dames
Dames

Reputation: 776

Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].

list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].

So to get the input list you might want to do something like this:

my_list = []
for i in range(int(input('Length: '))):
    my_list.append(int(input(f'Element {i}: ')))

and then continue with your code for summation.

A more pythonic way would be

my_list = [int(input(f'Element {i}: '))
           for i in range(int(input('Length: ')))]

For adding all the elements up you could use the inbuilt sum() function:

my_list_sum = sum(my_list)

Upvotes: 1

AKSHAY KUMAR RAY
AKSHAY KUMAR RAY

Reputation: 388

lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

Upvotes: 0

Related Questions