Python newbie

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Fri Sep 19 03:44:06 EDT 2008


On Fri, 19 Sep 2008 09:13:48 +0200, Mladen Gogala wrote:

> There are several questions:
> 
> 1) Why is the array "a" unchanged after undergoing a transformation with
>    map?

Because `map()` creates a new list and doesn't change the elements in `a`.

> 2) Why is it illegal to pass a built-in function "print" to map?

Because ``print`` isn't a function but a keyword.  This will be changed 
in Python 3.0.  On the other hand this use case is discouraged because 
`map()` builds a new list with the return value of the given function.  
So you would build a list full of `None`\s just for the side effect.

> 3) Why is the array "a" unchanged after undergoing an explicit
>    transformation with the "for" loop?

Because there is no explicit transformation.  The loop binds elements to 
the name `x` in your example and within the loop you rebind that name to 
another value.  Neither the name `x` nor the objects bound to it have any 
idea that the object might be referenced in some container object.

> 4) Is there an equivalent to \$a (Perl "reference") which would allow me
>    to decide when a variable is used by value and when by reference?

No, variables in Python are always name to object bindings.  Don't think 
of variables as boxes with names on it where you put objects in, or 
references to another box.  Think of objects and sticky notes with names 
on it.

> How can I make sure that
> for x in a: x=2*x
> 
> actually changes the elements of the array "a"?

Well, actually change the elements.  ;-)

Either:

for index, item in enumerate(sequence):
    sequence[index] = func(item)

Or:

sequence[:] = map(func, sequence)

But the need to do so doesn't seem to be that frequent.  Usually one just 
builds a new list instead of altering an existing one.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list