0

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)
11
  • So, you wrote this code. Okay. But what is the question? Commented Dec 25, 2020 at 11:43
  • 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 Commented Dec 25, 2020 at 11:44
  • 2
    No, not what the task is. What is your question related to the task and your code? Does it behave unexpectedly? Does it return an error message? Do you ask for help to improve it? Please elaborate on what you expect from SO users to help you with. Commented Dec 25, 2020 at 11:45
  • yes the output is not coming correctly. Commented Dec 25, 2020 at 11:46
  • The code i have written is wrong may be. Commented Dec 25, 2020 at 11:47

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

A =[] sum_element=0 totalElements_in_List = 5 # assuming it is for example 100 elements for iteration in range(5): A.append(int(input("Value #" + str(iteration) + " :"))) print(A) for element in A: sum_element=sum_element+element print(sum_element)
Can you pls run the above code? i guess not working.
It is working but instead of using for loop to get the sum you can use inbuilt function sum to get the sum of the list .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.