PEP 276 Simple Iterator for ints

David Eppstein eppstein at ics.uci.edu
Wed Nov 14 12:47:39 EST 2001


In article <MPxI7.134810$IR4.43476910 at news1.denver1.co.home.com>,
 "Rainer Deyke" <root at rainerdeyke.com> wrote:

> One thing bothers me about the Haskell syntax: using it to generate
> sequences of less than three elements just looks wrong.
> 
> [1, 2, ... 3] # This is obviously [1, 2, 3].
> [1, 2, ... 2] # What is this?  [1, 2]?
> [1, 2, ... 1] # [1]?
> [1, 2, ... 0] # []?
> 
> Another thing that bothers me is that I'm it's not obvious how the elements
> are evaluated.  This is not an issue in Haskell, but it is in Python:
> 
> def f(n):
>   print n
>   return n
> 
> for i in [f(0), f(1), ... f(5)]: pass
> 
> I assume that this prints 0, 1, and 5.  That makes sense from one
> perspective, but doesn't make sense at all from another perspective.
> Another example:
> 
> for i in [g() + 0, g() + 1, ... g() + 13]: pass
> 
> How often is 'g' called?  Once?  3 times?  14 times?

My assumption would be that the syntax [x, y, ... z] is equivalent to 
range(x,z+y-x,y-x).  This answers all of your questions:
[1,2,...2] = [1,2]
[1,2,...1] = [1]
[1,2,...0] = []
[f(0),f(1),...f(5)] prints 0, 1, 5 and returns [0,1,2,3,4,5]

[g()+0,g()+1,...g()+13] evaluates g() 3 times and (if g is 
side-effect-free) returns a list of 14 values
-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list