Hi,

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?

it isn't transformed. You get a new list as result.

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

because its not a function but a statement. If it was a function you
would call it print(x) not print x.

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

To understand this, python knows immutable objects and mutable.
Immutables are strings, tuples , ... and integers.
This means the operation above all create a new integer object in memory
and assign it to the name x (where you use = )

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

>>> l=range(10)
>>> for i in range(len(l)):
...     l[i]*=2
...     
>>> l
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


Cheers
Tino

Attachment: smime.p7s
Description: S/MIME Cryptographic Signature

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to