Lists

Peter Otten __peter__ at web.de
Mon Sep 15 03:36:46 EDT 2014


Christian Gollwitzer wrote:

> Am 15.09.14 04:40, schrieb Seymore4Head:
>> nums=range(1,11)
>> print (nums)
> 
>> I don't understand why the command nums=range(1,11) doesn't work.
>> I would think that print(nums) should be 1,2,3 ect.
>> Instead it prints range(1,11)
> 
> It does work, but in a different way than you might think. range() does
> not return a list of numbers, but rather a generator - that is an object
> which produces the values one after another. But you can transform it
> into a list:
> 
> print(list(nums))
> 
> should give you what you want.
> 
> Christian

I'd call range() an iterable. A generator is a specific kind of iterator.
The difference between iterable and iterator is that the latter cannot be 
restarted:

>>> def f():
...     yield 1
...     yield 2
... 
>>> g = f()
>>> list(g)
[1, 2]
>>> list(g)
[] # empty --> g is an iterator
>>> r = range(1, 3)
>>> list(r)
[1, 2]
>>> list(r)
[1, 2] # same as before --> r is an iterable





More information about the Python-list mailing list