[Tutor] General design question

Tim Golden mail at timgolden.me.uk
Wed Jul 2 11:54:58 CEST 2008

Paul Melvin wrote:
> If I have a set of numbers, or strings etc. which have been generated 
> and I then want to do something with them, for example a sum function 
> call.  Is the best way to put those items in a list, or similar 
> container, before applying the function.

Not only "best" but "necessary". the sum () builtin takes an
iterator -- often a list, but needn't be -- of numbers. Generally
you'll have the numbers in some container already. If you've used
range, then range already generates a list:


nums = range (5, 10) # the numbers 5, 6, 7, 8, 9 in a list
print sum (nums)


If you're getting a user to enter them (say) by raw_input, you'll
need to create your own list:


nums = []
while True:
  snum = raw_input ("Enter number (0 to finish): ")
  num = int (snum)
  if num == 0:
    nums.append (num)

print nums, "->", sum (nums)


(Obviously tons of assumptions in that code, which is just
a Noddy example)


More information about the Tutor mailing list