best way to do some simple tasks

Jp Calderone exarkun at intarweb.us
Wed Jan 29 18:46:31 EST 2003


On Wed, Jan 29, 2003 at 03:31:59PM -0800, Erik Lechak wrote:
> Hello all,
> 
> I am transitioning from perl to python.  I find myself trying to do
> many things in a perlish way.  Perl made many common tasks such as
> string manipulations easy (in a perlish sort of way).  So I was
> wondering if someone could suggest the "pythonish" way of doing these
> things.  I have read tons of documentation and can do all of the
> following tasks, but my code does not look "professional".
> 
> 
> 1) String interpolation of lists and dictionaries
>    What is the correct and best way to do this?
>    x =[1,2,3,4]
>    print "%(x[2])i blah" % vars() # <- does not work

  There have been many proposals regarding this.  Suffice it to say none
have yet made it into the language.

> 
> 2) Perform a method on each element of an array
>    a= ["  hello  ",  "  there  "]
>    
>    how do I use the string's strip() method on each element of the
> list?
>    

     a = [x.strip() for x in a]

  or

     a = map(str.strip, a)

> 3) What is the best way to do this?
> 
>    a=[1,2,3]
>    b=[1,1,1]
>    
>    how do I get c=a+b (c=[2,3,4])?
> 
     import operator
     c = map(operator.add, a, b)

> 
> 4) Why does this work this way?
>    d=[1,2,3,4,5]
>    for h in d:
>       h+=1
>    print d
>    >>>[1, 2, 3, 4, 5]
>    
>    Is there a python reason why h is a copy not a reference to the
> element in the list?

   h -is- a reference to the element in the list.  However, ints are
immutable.  h += 1 above is the same as "h = h + 1", which rebinds h to a
new int object.  If you want to change the elements of the list, iterate
over the indices of the list, like so:

    d = range(5)
    for h in range(len(d)):
      d[h] = d[h] + 1

  (soapbox) More generally, avoid using +=.  It leads to just this sort of
confusion - Is it mutating the object in place, or rebind the variable to a
new object?  It's often very difficult to tell.  Stick to the long form for
immutable objects, and use methods for mutable ones (.append() for lists,
for example).

  Jp

-- 
|     This 
|   signature
| intentionally
|    8 lines
|     long.
|  (So sue me)
---
-- 
 up 45 days, 3:49, 3 users, load average: 0.00, 0.07, 0.11
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20030129/740290e9/attachment.sig>


More information about the Python-list mailing list