0

I have the question where i need to find the sum of elements in the given numArray for .

But i am unable to get the desired output i want.

numArray = map(int, input().split()) 

sum_integer = 0
#write your logic to add these 4 numbers here

print(sum_integer) # Print the sum

My solution for that is

for i in range(len(numArray):
   sum_integer=sum_integer+numArray[i]

What is wrong with my solution? And i cannot change the way the input is taken.

Sathwik
  • 5
  • 5
  • 2
    don't loop though `range(4)`, loop through `numArray` – Paul H Jul 14 '19 at 15:28
  • 3
    OR `sum(map(int, input().split())` – Paul H Jul 14 '19 at 15:29
  • Not sure why you got downvoted. This is a legitimate question. The only thing that is missing is the error and traceback. – Mad Physicist Jul 14 '19 at 15:39
  • Do you get a SyntaxError or a TypeError? Your code as shown will not work at all. – MisterMiyagi Jul 14 '19 at 15:44
  • "TypeError: 'map' object is not subscriptable " This the error i am getting – Sathwik Jul 14 '19 at 15:47
  • Note that whoever wrote that exercise is misleading you. ``numArray`` is not an array/list - it is an iterator. – MisterMiyagi Jul 14 '19 at 15:47
  • Can you tell me what should i do then? and if you can also possibly tell me what is an iterator.I am new to programming – Sathwik Jul 14 '19 at 15:50
  • @Sathwik iterator, as opposed to a list, does not hold all the data in memory at any given moment. Rather it lets you *iterate* over it, fetching each element one by one and only occupying "one slot" in memory each time. This feature gives a lot of power for different scenarios. read more [here](https://stackoverflow.com/questions/4703390/how-to-extract-a-floating-number-from-a-string) – Tomerikoo Jul 14 '19 at 16:18

1 Answers1

3

Your problem is that map(int, input().split()) returns a map object which is an iterator, not a list. To illustrate, your code would work if you converted it to a list.

numArray = list(map(int, input().split()))

As the comments have point out, there are other, better ways to go about it. Changing the for loop to

for i in numArray:
    sum_integer += i

is a better solution, and doesn't force you to enter exactly 4 numbers. The other suggestion in the comments, to simply use

print(sum(map(int, input().split())))

which does all the steps in one line is far more concise.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Deepstop
  • 3,627
  • 2
  • 8
  • 21