Python newbie

Mladen Gogala gogala.mladen at gmail.com
Fri Sep 19 03:13:48 EDT 2008


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?
2) Why is it illegal to pass a built-in function "print" to map?
3) Why is the array "a" unchanged after undergoing an explicit
   transformation with the "for" loop?
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?

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"?


http://mgogala.freehostia.com



More information about the Python-list mailing list