Why is this?

Terry Hancock hancock at anansispaceworks.com
Sat Aug 13 01:25:16 EDT 2005


On Friday 12 August 2005 05:19 pm, Peter Mott wrote:
> Duncan Booth wrote:
> > So would you expect:
> > 
> >     random.seed(0)
> >     random.random() + random.random()
> > 
> > and:
> > 
> >     random.seed(0)
> >     random.random() * 2
> > 
> > to be the same? The first call to random() in each case returns the same 
> > result, but even though the source text is identical the second call 
> > in the addition returns something different. It is just the same with the 
> > lists.
> 
> I don't see that this bears on what I said at all.

It may be true that you don't see it, but it is also true
that it is exactly the same phenomenon.

In both cases you add '+' two distinct objects created by identical python
expressions, and are surprised that the result is not the same as creating
a single object from the same expression and doubling it with '*'.

a = []

is calling a list constructor, so it's basically a function call
(to a factory function that makes empty list objects).

a = [] + []

calls that function twice, creating two objects, then concatenating
them into a list.

b = [] * 2

calls the function only once, and then makes two references
to it. 

Which is just exactly what random is doing in the example
above, except that it's easier to see that that is a function call,
which is presumably the value of mentioning it. ;-)

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list