Python newbie

Steve Holden steve at holdenweb.com
Fri Sep 19 09:34:50 CEST 2008


Mladen Gogala wrote:
> I am a Python newbie who decided to see what that Python fuss is all about.
> Quite frankly, I am a bit perplexed. After having had few months of
> experience with Perl (started in 1994 with Perl v4, and doing it ever
> since) , here is what perplexes me:
> 
> perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;'
> 
> The equivalent in Python looks like this:
> 
> Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) 
> [GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> a=[1,2,3]
>>>> map((lambda x: 2*x),a)
> [2, 4, 6]
>>>> map((print),a)
>   File "<stdin>", line 1
>     map((print),a)
>              ^
> SyntaxError: invalid syntax
>>>> for x in a: print x
> ... 
> 1
> 2
> 3
>>>> for x in a: x=2*x
> ... 
>>>> for x in a: print x
> ... 
> 1
> 2
> 3
> 
> There are several questions:
> 
> 1) Why is the array "a" unchanged after undergoing a transformation with 
>    map?

Because you evaluated an expression in which a was a variable, giving an
entirely new object as a result.

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

Because at present "print" isn't a built-in function, it's a keyword
designating a specific statement type. Try using sys.stdout.write instead.

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

Because you aren't transforming a. You are extracting references to a's
elements into a separate variable and rebinding that variable to a new
value, leaving the references in a's elements pointing to the original
objects.

> 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. Python implicitly dereferences all names when using them to compute
values, and only uses them as references on the left-hand side of an
assignment.

Please note the above statement is contentious, and will likely bring a
horde of screaming fanatics of various flavors down on my head for
terminological inexactitude.

> PHP also allows changing arrays with "foreach" loop:
> #!/usr/local/bin/php
> <?php
> $a=array(1,2,3);
> foreach($a as &$x) { $x=$x*2; }
> array_walk($a,create_function('$a','print("$a\n"); '));
> ?>
> 
> How can I make sure that 
> for x in a: x=2*x 
> 
> actually changes the elements of the array "a"?
> 
By saying something like

a = [2*x for x in a]

You don't modify the individual elements, you create a new list and
rebind a to that. AIf you insist on changing the elements of a, a more
cumbersome alternative is

for i, x in enumerate(a):
  a[i] = 2+x

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list