0

Below code prints the desired output - 10

values = iter(range(1, 5))
sum(values)

Whereas if I add one more line of code between these lines, output changes to 0

values = iter(range(1, 5))
values_list = list(values)
sum(values)
  • 5
    If you exhaust the iterator with `list(values)` then there are no elements left for `sum`. – khelwood Apr 08 '19 at 06:30
  • The iterator is exhausted when you do `list()` on it. – Austin Apr 08 '19 at 06:30
  • Iterators are one time use objects, once you have performed an operation on them they are emptied. So when you do a list(values), the "values" iterator has no data. Now When you sum(values) , sum(0) = 0. Though you can still use sum(values_list) to get the sum – Sandeep Hukku Apr 08 '19 at 06:32

1 Answers1

1

Python iterators are exhaustable objects, meaning that they are used them up as you call them.

  • 1rst example:

    values = iter(range(1, 5))  # <- iterator is created
    sum(values)                 # <- all of it is used at once
    
  • 2nd example:

    values = iter(range(1, 5))  # <- iterator is created
    values_list = list(values)  # <- all of it is used at once
    sum(values)                 # <- nothing left to sum :(
    

If you want to use something over and over again, the iterator data type is not the one for you; use a list instead.

Ma0
  • 15,057
  • 4
  • 35
  • 65